Step 1: Set up the Repository
Set up a repository on GitHub and then clone it. More on this can be found here in the GitHub section of this site.
Step 2: Set up the Virtual Environment
Create a virtual envionment from your terminal so that all of your app requirements are kept together and will not create unwanted interactions with other libraries or requirements on your system as a whole.
python -m venv venv
You can then activate it (each time you load up your workspace) with:
.\venv\Scripts\activate
You can deactivate it at any time with:
.\venv\Scripts\deactivate
Step 3: Install Packages
Install the following packages required for the project.
pip3 install Flask-SQLAlchemy psycopg2
Flask-SQLAlchemy is an extension that integrates SQLAlchemy with your Flask app, which is an ORM for Python. It provides a database connection, an easy way to define models, and helper methods to query, insert, update, and delete records.
psycopg2 is a PostgreSQL database adapter for Python that allows your Flask app (via SQLAlchemy) to talk to a PostgreSQL database.
Troubleshooting
- If there is an error with finding some packages after installing. Use the following to check it is installed:
pip show Flask-SQLAlchemy
- If it keeps up, use ctrl + shift + p and change the python interpreter to another option and back again.
Step 4: Create an env.py File
Create an env.py file in your root directory to house your environment variables. Create it like this.
import os
os.environ.setdefault("IP", "0.0.0.0")
os.environ.setdefault("PORT", "5000")
os.environ.setdefault("SECRET_KEY", "[Your Secret Key]")
os.environ.setdefault("DEBUG", "True")
os.environ.setdefault("DEVELOPMENT", "True")
# Database not created yet:
# os.environ.setdefault("postgresql:///databasename")
Step 5: Create a .gitignore File
Make a .gitignore file in your root directory and add env.py into this file to keep your environment variables from being uploaded to GitHub.
Step 6: Set up the Project Folder
Create the application its own python package by making a new folder in root directory and give it the name of your project.
Create a file inside this folder named __init__.py. This file is a special Python file that initialises a Python package and is typically used to create the Flask application instance and set up configuration, extensions (like SQLAlchemy), and Blueprints.
Inside this file:
- Import os, flask, SQL modules, and an if statement to find the env.py. This if statement is important because when deployed, this file is not uploaded to GitHub and will thus not be found, causing an error without this statement.
- Your app will be an instance of the Flask app, so create this, and specify the environment variables that come from your env.py file.
- Create an instance of SQLAlchemy class and name it as db to use as your database.
- Import the URLs (known as routes in Flask) from your project. Note we have not created these yet. This is improted after creating the instance of the database (instead of the top of the file with the other imports), as it will rely on the above variables.
# Imports
import os
from flask import Flask
from flask_sqlalchemy import SQLAlchemy
if os.path.exists("env.py"):
import env
# Create an instance of the Flask class
app = Flask(__name__)
app.config[“SECRET_KEY”] = os.environ.get(“SECRET_KEY”)
app.config["SQLALCHEMY_DATABASE_URI"] = os.environ.get("DB_URL")
# Create an instance of the SQLAlchemy class
db= SQLAlchemy(app)
# Import routes from project_name
from project_name import routes
Step 7: Create the Routes
In Flask, routes define the URLs your web application will respond to, and map them to Python functions that handle the request and return a response.
Create a routes.py file in your project_name folder.
Inside this file:
- Import render_template, app, and your database.
- Create a route. I have added a basic one named home that will display a base.html file when called.
# Imports
from flask import render_template
from project_name import app, db
# Routes
@app.route("/")
def home():
return render_template("base.html")
Step 8: Create a run.py file
In the root directory create a run.py file. This file will import your flask apps and run the project.
# Imports
import os
from project_name import app
if __name__ == "__main__":
app.run(
host=os.environ.get("IP"),
port=int(os.environ.get("PORT")),
debug = os.environ.get("DEBUG")
)
-
The
if __name__" snippet checks if the run.py file is being run directly and if so runs the app with the required settings. -
host=os.environ.get("IP")gets the IP address from the environment variables defined in the env.py file via the __init__.py file. -
port=int(os.environ.get("PORT"))gets the port number (string) and converts it to an integer for use. -
debug=os.environ.get("DEBUG")tries to enable or disable debug mode based on the environment variable.
Step 9: Create the Templates
In your project_name folder, create a folder named templates. In here create base.html. This filename is called in the route defined in Step 7.
In base.html add some HTML boilerplate (if using VSCode you can type html:5 and press tab) and then add something to the body.
Step 10: Run your Project
Now run your project to make sure that it works. In the terminal enter:
python run.py
Then you can