-->
A Beginner's Complete Guide: Deploy Flask App with SQLite/ PostgreSQL Database on cPanel/ shared hosting

A Beginner's Complete Guide: Deploy Flask App with SQLite/ PostgreSQL Database on cPanel/ shared hosting

Back to top

Updated by Ashirafu Kibalama on May 16, 2024

A Comprehensive Guide to Deploying Flask App with SQLite/PostgreSQL Database on cPanel/Shared Hosting for Beginners




Deploying a Flask web application with a database on a shared hosting platform like cPanel can be challenging for beginners. 

I have deployed several Flask apps on shared hosting/ cPanel, and today, I want to showcase my experience. 

I have designed this Flask application to cover the challenges commonly faced when deploying a Flask app on shared hosting / cPanel.

I purchased this domain name and a shared hosting package from Namecheap to showcase this challenge.

This guide will simplify the process, enabling you to deploy your Flask application on a cPanel/ shared hosting environment with SQLite or PostgreSQL databases. 

Understanding the deployment process is crucial whether you're a student, developer, or business owner. We'll cover each step, from setting up Flask to deploying your application on cPanel, making it a valuable learning experience. 

So, let's dive in and explore the intricacies of deploying Flask apps on cPanel/shared hosting with ease.

Note:

If you encounter this error, your session cookie will be invalid. Please log in again.





Click Here to Learn How to Fix this Error: Your session cookie is invalid. Please log in again.



#You can also choose to watch my YouTube video for this specific blog post:



22 Steps To Guide You to Deploy A Flask App with SQLite/ PostgreSQL Database on cPanel/ Shared Hosting


Step 1) Modify your flask app within pycharm by Importing and using os (Miscellaneous operating system interfaces):


You can learn more about this modification by Clicking Here:

#before


#after


Note:
We commented out:
# app.config['SECRET_KEY'] = 'free425pythonhgfdte6Ocode3ERWfg4566ghghfgdlSihBXoxsource34SDE'

and replaced with:
app.config['SECRET_KEY'] = os.environ.get('FLASK_KEY')

Also, modify this:

#before


#after


You can learn more about this modification by Clicking Here:

Also, modify the debug mode:

#before


#after



Step 2) Having the correct Nameservers: 


For example:
If you purchased a domain from Namecheap and also have a shared hosting package with Namecheap, make sure that your nameservers are as below; otherwise, consult your hosting provider to avoid unnecessary errors:




Step 3) Setup python app:


Go to cPanel and click setup python app:







Click Create Application:













Note: Python version:

Please choose the recommended Python version when deploying your Flask Python app. For example: 3.6.15 (recommended).






Then click create:













Step 4) Go to cPanel and click File Manager:









In step 3) when we set up the Python app, we named the Application root as pythonexample. So, within the File Manager, look for the Application root name you created (pythonexample).



And click it.




Edit the passenger_wsgi.py









Click Edit:




So replace all that code with this code below:




Note: 

We are using from main: I have a main.py in my Flask app, so modify this accordingly.





Then Click Save to save changes:






Step 5) Upload your Flask application:


Note: If you encounter this error:

Click Here to fix








Click Here to fix

The File Manager Does Not Support Extracting This Type Of Archive. / An Error Occurred. Your Account May Be Over Its Quota, or You Attempted To Upload a Folder. Click Here to fix











Click reload for the page to refresh/ reload:



Go on and extract the file:







Click extract files and then click close:





Again reload or refresh this page:



Open your file and move all files to:






















Step 6) Check for error logs in the cpanel flask Python:


Note:

This step is very important because it is where we get the error information to debug your Flask Python app. And whenever I say go to your error logs, I mean to follow this step:


1- Open your flask python app directory in cpanel:




2- Look for stderr.log: 




3- Right-click and then click view:




4- Scroll to the end of the page and debug your code depending on information from the last lines on this page:






Note:

This step is crucial because it is where we get the error information to debug your Flask Python app. And whenever I say go to your error logs, I mean to follow this step:


Step 7) Go to setup python app and edit your flask python app:








Click the pen-like symbol to edit the app:





Scroll down until you see the Configuration files:




Step 8) Add requirements.txt:







Then click Add and click Run Pip Install.








Then click requirements.txt.









Error: Click Show More to learn more about the error.


Step 9) Fix error(Optional) only if you encounter this error: ERROR: Failed building wheel for greenlet
ERROR: Could not build wheels for greenlet, which is required to install pyproject.toml-based projects






We will solve this error by building wheels for Greenlet, which is required to install the project. Tool-based projects fix errors:



1- Open terminal in cpanel:


Note: If you do not know where to find the terminal in cPanel, Click Here To Find Out:








2- Go to setup python app and click this command, then paste it into your terminal:








Just click the virtual environment to copy them to clipboard the line:

  source /home/pythylbd/virtualenv/pythonexample/3.9/bin/activate && cd /home/pythylbd/pythonexample




Then past it into the terminal:









Then click enter:




3- Update pip and setup tools:

Sometimes, outdated versions of pip and setup tools can cause issues. You can update them using the following commands:



pip install --upgrade pip
pip install --upgrade setuptools





Click enter to continue:




4- Try installing the wheel:

The wheel package is often needed to build binary packages. You can install it using pip:



pip install wheel







5- Finally, pip install --only-binary :all: greenlet:



pip install --only-binary :all: greenlet








Running pip install --only-binary :all: Greenlet should attempt to install the Greenlet package without trying to build it from the source. 

This command specifies that only pre-built binary distributions should be used if available.


If pre-built binaries are available for your platform and Python version, this command should succeed without encountering the "Could not build wheels for greenlet" error.


However, you might still encounter the same error if no pre-built binaries are available for your platform. 


In that case, you may need to investigate further or try alternative solutions, such as those mentioned in the previous response.


Please run the command and let me know if you encounter any issues.


Again, Click Run Pip Install and click requirements.txt, but close the error shown first.










Finally, click save:




Python application saved:




Step 10) Fix error(Optional) only if you encounter this error: ERROR: No matching distribution found for Flask_WTF==1.2.1.





The system automatically informs you that the provided version does not match the available versions and displays the expected versions needed. 

To fix this ERROR: No matching distribution was found for Flask_WTF==1.2.1. Look at the version displayed by the system in the error pop box. 


So, in this case, the last version is 1.0.1, so change Flask_WTF==1.2.1 to Flask_WTF==1.0.1.





#before change
#requirements.txt 




Save changes in the requirements.txt after changes.

#after change
#requirements.txt


Again, Click Run Pip Install and click requirements.txt, but close the error shown first.




Step 11) Fix error(Optional) only if you encounter this error: ERROR: No matching distribution found for WTForms==3.0.1.




The system automatically notifies you that the provided version does not match the available versions within the system and displays the expected versions required. 


To fix this ERROR: No matching distribution was found for WTForms==3.0.1, look at the version displayed by the system in the error pop-up box. 


So, in this case, the last version is 3.0.0, so change WTForms==3.0.1 to WTForms==3.0.0.


#before change

#requirements.txt




#after change

#requirements.txt



Click save changes.


Again, Click Run Pip Install and click requirements.txt, but close the error shown first.


Note: all errors of a similar nature have the exact handling, and in this post, we have given two examples to help you better understand. Please let us know in the comment section if you like our work and appreciate our effort.





Once the pip is successful, Click save to save all changes:


Step 12) Fix ERROR: Could not find a version that satisfies the requirement alembic>=1.9.0 (from flask-migrate) or ERROR: No matching distribution found for alembic>=1.9.0.


If you ever encounter this: 


Error
ERROR: Could not find a version that satisfies the requirement alembic>=1.9.0 (from flask-migrate) (from versions:
0.1.0, 0.1.1, 0.2.0, 0.2.1, 0.2.2, 0.3.0, 0.3.1, 0.3.2, 0.3.4, 0.3.5, 0.3.6, 0.4.0,
0.4.1, 0.4.2, 0.5.0, 0.6.0, 0.6.1, 0.6.2, 0.6.3, 0.6.4, 0.6.5, 0.6.6, 0.6.7, 0.7.0, 0.7.1,
0.7.2, 0.7.3, 0.7.4, 0.7.5.post1, 0.7.5.post2, 0.7.6, 0.7.7, 0.8.0, 0.8.1, 0.8.2,
0.8.3, 0.8.4, 0.8.5, 0.8.6, 0.8.7, 0.8.8, 0.8.9, 0.8.10, 0.9.0, 0.9.1, 0.9.2, 0.9.3, 0.9.4,
0.9.5, 0.9.6, 0.9.7, 0.9.8, 0.9.9, 0.9.10, 1.0.0, 1.0.1, 1.0.2, 1.0.3, 1.0.4, 1.0.5, 1.0.6,
1.0.7, 1.0.8, 1.0.9, 1.0.10, 1.0.11, 1.1.0, 1.2.0, 1.2.1, 1.3.0, 1.3.1, 1.3.2, 1.3.3, 1.4.0,
1.4.1, 1.4.2, 1.4.3, 1.5.0, 1.5.1, 1.5.2, 1.5.3, 1.5.4, 1.5.5, 1.5.6, 1.5.7, 1.5.8, 1.6.0, 1.6.1,
1.6.2, 1.6.3, 1.6.4, 1.6.5, 1.7.0, 1.7.1, 1.7.2, 1.7.3, 1.7.4, 1.7.5, 1.7.6, 1.7.7)
ERROR: No matching distribution found for alembic>=1.9.0

This means there is an issue with finding the appropriate version of the Alembic library that satisfies the requirement for flask migration. One potential solution is to ensure that your Python environment is up to date and then try installing Alembic separately before installing flask-migrate. 


Here are the steps you can follow:


2 Ways To Fix ERROR: Could not find a version that satisfies the requirement alembic>=1.9.0 (from flask-migrate) or ERROR: No matching distribution found for Alembic >=1.9.0.


1- To Install Alembic separately via Terminal as we have illustrated using the Terminal above in several steps:


pip install alembic


2- Then install flask-migrate via Terminal as we have illustrated using the Terminal above in several steps:


pip install Flask-Migrate

This should resolve the issue.


Step 13) Go to cPanel and look for Databases, then PostgreSQL Database Wizard and create your database.










Create the database, for example, pythonexample.




Click create database:




Create database user with username and password:




Remember to save your database info somewhere.









Step 14) Connect to your PostgreSQL Database in main.py or app.py, depending on your Flask python app:









Edit main.py:

#before editting



#after editting




Click save changes to save.


Step 15) Add Environment variables such as the FLASK_KEY. (Within the Setup python app)


 Remember that we replaced this:


# app.config['SECRET_KEY'] = 'free425pythonhgfdte6Ocode3ERWfg4566ghghfgdlSihBXoxsource34SDE'

With this:


app.config['SECRET_KEY'] = os.environ.get('FLASK_KEY')


So from these two lines, FLASK_KEY = free425pythonhgfdte6Ocode3ERWfg4566ghghfgdlSihBXoxsource34SDE





Click Add Variable.







Name: FLASK_KEY

Value: free425pythonhgfdte6Ocode3ERWfg4566ghghfgdlSihBXoxsource34SDE



Then click Done:



Then Click save to save changes:






Wait for a few minutes for the system to save:





Step 16) Test your Flask Python app by clicking open as illustrated below:











Step 17) Go to your error logs, and if you are not familiar with this, read step 6) for more info: 





Remember to focus on the last line on this page first.

Error: ImportError: cannot import name 'DeclarativeBase' from 'sqlalchemy.orm'


Step 18) Fix ImportError: cannot import name 'DeclarativeBase' from 'sqlalchemy.orm' / class Base(DeclarativeBase): NameError: name 'DeclarativeBase' is not defined.




Both of these errors have the exact handling or solution.

You're encountering import errors and a NameError while working with SQLAlchemy's ORM. 


These errors are due to incorrect import statements or missing definitions.

Here's how you can adequately define your SQLAlchemy base class and import it:


2 Ways To Fix ImportError: cannot import name 'DeclarativeBase' from 'sqlalchemy. Orm' / class Base(DeclarativeBase): NameError: name 'DeclarativeBase' is not defined.


1- import declarative_base from sqlalchemy.ext.declarative.


from sqlalchemy.ext.declarative import declarative_base


2- create a base class Base using declarative_base().



# create a base class Base using declarative_base().
Base = declarative_base()


# Before Creating a base class Base using declarative_base().




# After Creating a base class Base using declarative_base().





So we comment this:



and replace with this:





Make sure that your import statements are correct. Do not use the DeclarativeBase class; it should be declarative_base() in SQLAlchemy. Also, ensure that SQLAlchemy is installed correctly in your environment.


Comment  DeclarativeBase from this line: 


from sqlalchemy.orm import relationship, DeclarativeBase, Mapped, mapped_column


#Commenting DeclarativeBase.


# from sqlalchemy.orm import relationship, DeclarativeBase, Mapped, mapped_column
from sqlalchemy.orm import relationship, Mapped, mapped_column



Click save changes:






Restart or Stop the app, Start your Flask Python app:






Then go and rerun your Flask Python app:

We see that we are still getting an internal server error. Again, go to your error logs and hard-refresh the error logs page to see another mistake at the end of the error page. Always remember that.










I have fixed this error, saved the changes and restarted the Flask Python app; however, when I refresh the error logs page, I still get the same error. Make sure that you have fixed the error correctly, saved the changes and restarted the Flask Python app. If so, keep refreshing the error log page 3 - 4 times until changes are reflected. This always happens from my own experience, so do not panic. You are on the right path.

Note: This blog post is for beginners concerning this deployment, and it's more practical, so I want to ensure you get all the points that will challenge you at any moment. However, if you value my work, please comment in the comment section to improve this post. For example, excellent work or any comment will add value.

The ImportError: cannot import name 'DeclarativeBase' from 'sqlalchemy.orm is now solved. However, we are getting another error:




Step 19) Fix ImportError: cannot import name 'mapped_column' from 'sqlalchemy.orm' / ImportError: cannot import name 'Mapped' from 'sqlalchemy.orm'.



The error message "ImportError: cannot import name 'mapped_column' from 'sqlalchemy.orm'" typically indicates that you're trying to import a symbol (mapped_column) from the sqlalchemy.orm module that doesn't exist. 


You may have meant to import a different symbol or use an outdated SQLAlchemy version.

In recent versions of SQLAlchemy, there is no mapped_column directly in the sqlalchemy.orm module. 

Instead, use Column from the sqlalchemy module. Here's how you can fix it:


from sqlalchemy import Column


#Before removing mappad_column and Mapped




#After removing mapped_column and Mapped.





If you were specifically looking for a mapped column in the SQLAlchemy ORM context, refer to the Column class within a mapped class definition. Also, remove Mapped to avoid further errors.

Here's an example:  


#Before removing Mapped and mapped_column from all models.




#After removing Mapped and mapped_column from all models.




Change all your models. This is an example of a class Posts Model.


Make sure you have the necessary version of SQLAlchemy installed. You can update it using pip:


Click save changes:







Restart or Stop the app, Start your Flask Python app, and refresh the error log page:




Then go and rerun your Flask Python app:

We see that we are still getting an internal server error. Again, go to your error logs and hard-refresh the error logs page to see another mistake at the end of the error page. Always remember that.


The ImportError: cannot import name 'mapped_column' from 'sqlalchemy.orm' / ImportError: cannot import name 'Mapped' from 'sqlalchemy.orm' is now solved. However, we are getting another error:





Step 20) Fix ModuleNotFoundError: No module named 'flask_migrate':





If you're encountering a ModuleNotFoundError for flask_migrate, it means that Flask-Migrate, a Flask extension for database migrations, is not installed in your Python environment. To fix this, you need to install Flask-Migrate using pip.


In your terminal or command prompt, run this command:


pip install Flask-Migrate


Open your terminal in cPanel or Click Here for more info about where the terminal is in cPanel.





Just click the virtual environment to copy them to clipboard the line:

  source /home/pythylbd/virtualenv/pythonexample/3.9/bin/activate && cd /home/pythylbd/pythonexample




Then past it into the terminal:









Press Enter:



Then pip install Flask-Migrate





Success:

Ensure you are using the correct virtual environment if you use one. After installing Flask-Migrate, you can import it into your Python code without encountering the ModuleNotFoundError.


Now go on and rerun your flask app:



We highly recommend you read this if you encounter this challenge:


How To Fix: The Database Is Created Outside Of The Instance Folder Flask Python




Step 21) Create a path to the SQLite database or PostgreSQL Database file to test the database connection (Optional):




Click here to learn more about this path.


We highly recommend you read this if you encounter this challenge:


How To Fix: The Database Is Created Outside Of The Instance Folder Flask Python


If you want to test the connection to your SQLite database or PostgreSQL Database file, you can create a path to the file. This step is optional.


Click here to learn more about this path.




This is the SQLite database file:  "sqlite:///our_posts.db".

Add this to code:


# OTHER CODES ABOVE

# Database configuration
DB_HOST = "localhost"
DB_PORT = 5432
DB_NAME = 'pythylbd_pythonexample'
DB_USER = 'pythylbd_example'
DB_PASSWORD = '{QF%.H=Hp!!g'

# Database connection URL
DB_URL = f'postgresql://{DB_USER}:{DB_PASSWORD}@{DB_HOST}:{DB_PORT}/{DB_NAME}'


# Replace 'username', 'password', 'localhost', and 'database_name' with your PostgreSQL credentials


# path to the SQLite database file.
DATABASE_URI = 'sqlite:///instance/our_posts.db'

# Check if the database file exists
if not os.path.exists(DATABASE_URI):
print(f"Error: SQLite database file '{DATABASE_URI}' not found.")
# You might want to handle this error condition appropriately,
# such as creating the database file or exiting the application.

# Check permissions of the database file
if not os.access(DATABASE_URI, os.R_OK | os.W_OK):
print(f"Error: Insufficient permissions to access SQLite database file '{DATABASE_URI}'.")
# You might want to handle this error condition appropriately,
# such as modifying file permissions or exiting the application.

# Print/debug the SQLAlchemy connection string
print("SQLAlchemy Connection String:", DATABASE_URI)

# Create SQLAlchemy engine
engine = create_engine(DATABASE_URI)

# Attempt to connect to the database
try:
# This will attempt to connect to the database using the provided URI
connection = engine.connect()
print("Connected to the database successfully!")
connection.close()
except Exception as e:
print("Failed to connect to the database:", e)


# CREATE DATABASE
#class Base(DeclarativeBase):
# pass


# create a base class Base using declarative_base().
Base = declarative_base()

# OTHER CODES BELOW


So, when you run your Flask app and go to error logs, you will know whether or not the database connection is successful.




However, you must add these lines to your requirements.txt.



#requirements.txt



 

Step 22) Finally, thoroughly test every URL route of your Flask Python app:


It is essential to thoroughly test every URL route in your Flask Python app to ensure no errors occur. If errors occur, refer to the error logs and debug accordingly.





Finally, Successful:


We highly recommend you read this if you encounter this challenge:


How To Fix: The Database Is Created Outside Of The Instance Folder Flask Python



Conclusion:

Deploying a Flask app with either a SQLite or PostgreSQL database on cPanel or shared hosting may seem intimidating. 

However, this guide thoroughly explains 22 comprehensive steps that make it an achievable task even for beginners. 


By carefully following each step, you can successfully set up your environment, configure your database, and deploy your Flask application, opening up opportunities to share your projects with the world. 


Remember to troubleshoot issues patiently, utilize available resources, and continuously improve your skills. With determination and persistence, you'll soon find yourself adept at deploying web applications on various hosting platforms. 


So, embark on this journey confidently, and let your creativity flourish in web development. 


Please let us know if you find value in this blog post or if we should include a point.


"I appreciate your comment as it provides value to this post."


"Thank you, and I hope you have a wonderful time. Happy coding!"


Related Posts:


How Do I Add or Connect a Flask Python Website To Google Search Console? 


How Do I Add or Connect Google Analytics to a Flask Python Website? 


How To Fix: The Database Is Created Outside Of The Instance Folder Flask Python


With an Example: How To Create an XML Sitemap Flask Python? 


Other Posts:


What To Look For While Selecting Any Web Hosting Company 


What is Better Than cPanel?


When To Use cPanel? 


Is cPanel Good for Hosting? 


Why do People use cPanel? 


What are the Disadvantages of cPanel Hosting? 


How To Fix: Your Session Cookie is Invalid. Please Log in Again./ Why is cPanel Login Invalid?


Why is there no terminal in cPanel?/ Enable Terminal in Cpanel on Shared Hosting like Namecheap 


How To Approve or Unapproved Results in Flask Python example.


10 When should you use PostgreSQL over SQLite?