Ensure that you have the following installed on your machine:
-
Python: Check if Python is installed by running in your terminal:
python --version
If it's not installed, download it from here.
-
PyCharm: Download and install PyCharm from here.
Note: The following steps are specific to PyCharm, but you can adapt them to other IDEs or text editors. See the versions used for this tutorial:
- Python: 3.12.5
- PyCharm: 2024.2.3 (Community Edition)
-
Open PyCharm.
-
Click on New Project.
-
Choose Pure Python from the left sidebar.
-
Set your project Name (e.g.,
my_flask_app
) and location (e.g.,~/usr/<username>/PycharmProjects
). -
Tick the box that says Create Git Repository if you want to use version control (optional).
-
Select the Project venv option for Interpreter type so that it uses a virtual environment (the default option).
-
Select the Python version you want to use (usually the default one detected in the system).
-
Click Create.
-
Right-click on the project root (
my_flask_app
). -
Select New > Directory and create a folder named
app
. -
Create a new Python file in the project root (
my_flask_app
) directory namedapp.py
. (Right-click on the project root and select New > Python File). This file will be the entry point for our Flask application. -
The file opens in the editor on the right. Let's edit the file with the following code:
from app import app if __name__ == '__main__': app.run(debug=True)
Realize that the app after import is underlined with red squiggly lines because it doesn't know how to import from the app directory yet. Let's fix that below.
-
Create a new Python file in the
app
directory named__init__.py
. This is a special file that tells Python that theapp
directory should be treated as a package. This will initialize the Flask application. -
Add the following code to the
__init__.py
file:from flask import Flask
You will realize some squiggly lines under Flask because it doesn't know where to import it from. Let's fix that below.
-
Open the Python Packages in PyCharm (usually located at the bottom left panel of the window).
Only pip in installed. We need to install Flask.
-
Open the terminal in PyCharm (usually located at the bottom of the window). Ensure your virtual environment is activated. You should see the name of your virtual environment in the terminal prompt.
(.venv) ~\PycharmProjects\my_flask_app
-
Install Flask by running the following command:
pip install flask
-
Once Flask is installed, you should see it and its dependencies listed in the Python Packages section alongside
pip
:MarkupSafe
itsdangerous
colorama
blinker
Werkzeug
Jinja2
click
flask
Realize that the squiggly lines under Flask and app have disappeared because PyCharm now recognizes the Flask package.
-
Create a new Python file in the
app
directory namedapp_factory.py
. This file will contain the function to create the Flask application instance. It will also import theapp
instance from the__init__.py
file. It will serve as a workaround to the circular import and redundancy issue that arises when importing theapp
instance in theapp.py
file. Write the following code in theapp_factory.py
file:from flask import Flask def create_app(): app = Flask(__name__) return app
-
In the
__init__.py
file, import thecreate_app
function from theapp_factory.py
file and create theapp
instance:from .app_factory import create_app app = create_app()
This should start our app.
We will create the routes and templates for our application. We will start with routes - this is like the brain of our application.
-
Right-click on the
app
directory and create a new file namedroutes.py
. This file will contain the routes for our application. Have the below code in theroutes.py
file:from flask import render_template from . import app @app.route('/') def index(): return render_template('index.html')
-
Create a new directory in the
app
directory namedtemplates
. This directory will contain the HTML templates for our application.- Right-click on the project root (
my_flask_app
). - Select New > Directory and create a folder named
templates
.
- Right-click on the project root (
-
Inside the
templates
folder, create a new HTML file namedindex.html
. This file will be the homepage of our application. Add the following code:<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Your Name</title> </head> <body> <h1>Welcome to Your Name's Website</h1> </body> </html>
Replace
Your Name
with your name. -
In the
__init__.py
file, import theroutes
module to register the routes with the Flask application:from . import routes
-
Let's also add a secret key to the
app
instance in the__init__.py
file. This is used to keep the client-side sessions secure. Add the following line to theapp
instance in the__init__.py
file:app.secret_key = 'your_secret_key'
_Replace
your_secret_key
with an environment variable of your choice. _
Here's how we will run this application:
-
Open the terminal in PyCharm.
-
Ensure your virtual environment is activated.
-
Run the following command to start the Flask development server:
python app.py
You should see the following output:
* Serving Flask app 'app.app_factory' * Debug mode: on WARNING: This is a development server. Do not use it in a production deployment. Use a production WSGI server instead. * Running on http://127.0.0.1:5000 Press CTRL+C to quit * Restarting with stat * Debugger is active! * Debugger PIN: 123-456-789
Anything done on the website will show up here.
-
Open your browser and navigate to
http://127.0.0.1:5000/
to view your website. -
Make some changes to the website. The change will reflect since this is development server.
-
Open
index.html
and change the<h1>
element to<h1>Welcome to Your Name's Best Website</h1>
-
Go to the webpage and refresh the page.
-
The new content should appear. The activity should also be displayed in your terminal as well.
-
To add static files like pictures, here's what to do:
-
Right-Click on the
app
directory and create a new directory namedstatic
. This directory will contain the static files for our application. -
Inside the
static
folder, create a new directory namedassets
. This directory will contain the images for our application. -
Add an image to the
assets
directory. You can download an image from the internet or use any image you have on your computer. -
In the
index.html
file, add the following code to display the image:<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Your Name</title> </head> <body> <h1>Welcome to Your Name's Website</h1> <img src="{{ url_for('static', filename='assets/image.jpg') }}" alt="Your Name"> </body> </html>
Replace
image.jpg
with the name of the image you added to theassets
directory. -
Run the application again by running the
app.py
file or refresh your browser if the server is still running.The image should be displayed on the homepage of your website.
-
Let's make the image smaller by changing the line in
index.html
to the below:<img src="{{ url_for('static', filename='assets/image.jpg') }}" alt="Your Name" width="300">
The image should now be smaller.
If you hadn't initialized a Git repository when creating the project, you can do so now(In Pycharm).
-
Click on the VCS menu on the top bar.
-
Select Enable Version Control Integration....
-
In the dialog that appears, select Git from the list of version control systems and click OK.
-
You should see the Git icon in the top right corner of the PyCharm window, just below the project folder icon.
If you had initialized a Git repository when creating the project, you can commit your changes by following these steps:
-
Right-click on the project root and select Git > Add to add all the files to the staging area.
-
Open the Commit Changes dialog by clicking on the Commit icon in the top right corner of the PyCharm window just below the project folder icon.
-
Select on the changes checkbox that appears to select files. In the Commit Changes panel that appears, enter a commit message and click Commit. You can also click on the Commit and Push button to push the changes to a remote repository if you had connected to one. If you hadn't, you can do so by:
-
Click on the VCS / Git menu on the top bar.
-
Select GitHub > Share Project on GitHub
-
Follow the prompts to connect to your GitHub account and create a new repository if you hadn't connected. If you had, then proceed.
-
Enter the repository name and description (optional) and click Share. Uncheck
private
if you want the repository to be public.
-
We want to add different pages that can be navigated to.
-
Add the following to the
routes.py
file:@app.route('/about') def about(): return render_template('about.html')
This will create a new route for the
/about
URL that will render theabout.html
template. -
Create a new HTML file in the
templates
directory namedabout.html
. Add the following content to the file:<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>About</title> </head> <body> <h1>About Me</h1> </body> </html>
-
Let's take a step further and add
base.html
to thetemplates
directory. This file will contain the common elements of all the pages. Add the following content to the file:<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Flask Example</title> </head> <body> {% block content %}{% endblock %} </body> </html>
-
Update the
index.html
andabout.html
files to extend thebase.html
file. Replace the content of theindex.html
file with the following:{% extends 'base.html' %} {% block content %} <h1>Welcome to Your Name's Website</h1> <img src="{{ url_for('static', filename='assets/image.jpg') }}" alt="Your Name" width="300"> {% endblock %}
Replace the content of the
about.html
file with the following:{% extends 'base.html' %} {% block content %} <h1>About Me</h1> {% endblock %}
If you refresh the page in the browser, it will still work. See the change in the tab title. It picks the
base.html
title.If you navigate to
http://127.0.0.1:5000/about
, you should see the content of theabout.html
file. -
Let's add navigation links to the
base.html
file. Update thebase.html
file with the following content:(You can use Copilot in PyCharm to generate the code)
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Flask Example</title> </head> <body> <nav> <a href="{{ url_for('index') }}">Home</a> | <a href="{{ url_for('about') }}">About</a> </nav> {% block content %}{% endblock %} </body> </html>
The navigation links should now appear on all pages.
-
Let's give the application a basic bootstrap look. We will use Bootstrap 5 (currently v5.3 as at the writing of this walkthrough). See here for more information: Latest Bootstrap
Change the
base.html
file to the following:<!DOCTYPE html> <html lang="en" xmlns="http://www.w3.org/1999/html"> <head> <meta charset="UTF-8"> <title>Flask Example</title> <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-QWTKZyjpPEjISv5WaRU9OFeRpok6YctnYmDr5pNlyT2bRjXh0JMhjY6hW+ALEwIH" crossorigin="anonymous"> </head> <body class="container"> <header> <!-- Brand Name --> <h1 class="text-center m-0 display-2">Flask App</h1> <!-- Navigation Menu --> <nav class="d-flex justify-content-center py-3"> <ul class="nav nav-pills nav-fill gap-2 p-1 small bg-primary rounded-5 shadow-sm" id="pillNav2" role="tablist" style="--bs-nav-link-color: var(--bs-white); --bs-nav-pills-link-active-color: var(--bs-primary); --bs-nav-pills-link-active-bg: var(--bs-white);"> <li class="nav-item" role="presentation"> <a class="nav-link {% if request.endpoint == 'index' %}active{% endif %} rounded-5" id="home-tab" href="{{ url_for('index') }}" role="tab" aria-selected="true">Home</a> </li> <li class="nav-item" role="presentation"> <a class="nav-link {% if request.endpoint == 'about' %}active{% endif %} rounded-5" id="about-tab" href="{{ url_for('about') }}" role="tab" aria-selected="false">About</a> </li> </ul> </nav> </header> <!-- Flask dynamically loads the page content --> <main class="row justify-content-center"> {% block content %} {% endblock %} </main> <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/js/bootstrap.bundle.min.js" integrity="sha384-YvpcrYf0tY3lHB60NNkmXc5s9fDVZLESaAA55NDzOxhy9GkcIdslK1eN7N6jIeHz" crossorigin="anonymous"></script> </body> </html>
{% if request.endpoint == 'index' %}active{% endif %}
has been added for extra functionality required in bootstrap theme used. (A little advanced)Your
index.html
andabout.html
should be like the following:index.html
{% extends 'base.html' %} {% block content %} <h2 class="text-center display-4">Welcome to Your Name's Website</h2> <img src="{{ url_for('static', filename='assets/image.jpg') }}" alt="Your Name" width="200"> {% endblock %}
about.html
{% extends 'base.html' %} {% block content %} <h2 class="text-center display-4">About Your Name</h2> {% endblock %}
Your webpage should have a look similar to the ones below:
-
You can now commit your changes to Git and push your changes to GitHub if you have it set up.
You can also add more pages and styles to your application.
You have successfully created a simple Flask application with multiple pages and a basic Bootstrap theme. You can now build on this foundation to create more complex web applications using Flask.
This is a basic guide to get you started with Flask. You can explore more features and functionalities of Flask to build more advanced web applications.
You can find this example in this repository
Happy coding! π
Before starting, ensure you have the following installed:
- Heroku CLI
- Python
- PyCharm
- MySQL Workbench
- A Heroku account
Note: The following steps are specific to PyCharm, but you can adapt them to other IDEs or text editors. See the versions used for this tutorial:
- Python: 3.12.5
- PyCharm: 2024.2.3 (Community Edition)
- MySQL Workbench: 8.0.38
- Heroku CLI: heroku/9.3.0 win32-x64 node-v16.20.2
- Heroku Account: Free tier
- Operating System: Windows 11
- Open your browser and navigate to Heroku.
- Log in to your Heroku account.
- Click on the New button and select Create New App.
- Enter a unique name for your app and click on the Create App button.
- Your app will be created, and you will be redirected to the app dashboard. Take note of the app name as you will need it later.
- Click on the Resources tab in the Heroku app dashboard.
- In the Add-ons section, search for JawsDB MySQL. Click on the JawsDB MySQL add-on to add it to your app.
- In the pop-up window, be sure to select the Kitefin Shared - Free plan and click on the **Submit Order Form
- You will see the JawsDB MySQL add-on listed in the Add-ons section. Click on the JawsDB MySQL add-on to view the details in Kitefin Server Dashboard.
- You will see the connection details for the JawsDB MySQL database, including the username, password, host, and database name.
-
Log in to your Heroku account via the CLI:
heroku login
-
Create a new Heroku app:
heroku create <your-app-name>
Replace with a unique name for your app.
This command will create a new Heroku app and associate it with a git repository.
-
Add the JawsDB MySQL add-on to your Heroku app:
heroku addons:create jawsdb:kitefin -a <your-app-name>
-
To get the connection URL of the MySQL database, run:
heroku config:get JAWSDB_URL -a <your-app-name>
This will return the MySQL connection URL. You'll use this later to connect to MySQL Workbench and in your Flask app.
- Open MySQL Workbench on your local machine.
- Click on the + icon next to MySQL Connections to create a new connection.
- Enter the connection details provided by JawsDB MySQL in the Connection Name, Hostname, Port, Username, and Password fields. Remember to replace the placeholders with the actual values provided by JawsDB MySQL. Note: Set the username first before the password to properly store your password in the vault.
- Click on Test Connection to verify the connection. If the connection is successful, click on OK to save the connection.
- You should see the new connection listed under MySQL Connections. Double-click on the connection to open it and view the databases and tables.
- You can now create tables in the new database by right-clicking on the database and selecting Create Table.
- In the table use the following details:
- Table Name:
basic
- Columns:
basic_id
Click on the checkbox (PK - for primary key, NN for Not Null, AI for Auto Increment) You should see a key icon on basic_id indicating it's the primary key.first_name
DatatypeVARCHAR(45)
last_name
DatatypeVARCHAR(45)
- Table Name:
- Click on Apply to preview the SQL query and then click on Apply again to create the table.
- To edit the table, expand the table under the database. Hover over the table name. If you click on the wrench, you can edit the table. If you click on the table icon, I can put data into the table.
- In the result grid, you can add data to the table. Make sure to click on the Apply button to save the data else it won't be applied. Note that the basic_id auto increments, and we don't have to input value into it because it is a primary key.
For this walkthrough, we will deploy a new flask application that has not being connected with GitHub as we will use Heroku Git.
-
Create a new Pycharm project and name it
my-flask-app
. Use the same steps as in the previous walkthrough. Do not use git control version. You can copy the previous project into the new project and use it as the starting point. -
Open the terminal in PyCharm of the project. Ensure your virtual environment is activated. We will use the steps outlined in the Deploy tab in Heroku app dashboard.
-
Login to Heroku CLI using the command:
heroku login
-
Initialize the Git repository in the root directory of your Flask application by running the following command:
git init heroku git:remote -a <your-app-name>
Replace
<your-app-name>
with the name of your Heroku app. -
Add the files to the staging area and commit by running the following command:
git add . git commit -am "Initial commit"
Now we're ready to push this app to Heroku
-
Push the changes to the Heroku remote repository by running the following command:
git push heroku main
You can use
master
instead ofmain
if you are using the master branch. You will get an error if your app was blank. You can check your logs in the dashboard, More > View Logs to see the error. -
Let's modify our application by adding some files to make the deployment successful.
-
Create a new file in the root directory of your Flask application named
Procfile
. This file will contain the command to run the Flask application on Heroku. Add the following code to the file:web: gunicorn app:app
This will tell Heroku to run the Flask application using the
gunicorn
web server. -
Create a requirements file by running the following command in the terminal:
pip freeze > requirements.txt
This will generate a
requirements.txt
file containing the Python packages required by your Flask application. This file will be read by Heroku to install the necessary packages.
-
-
Push the changes to the Heroku remote repository by running the following command:
git push heroku main
This time it is successful. You should see the progress in the terminal.
-
Once the deployment is complete, you will see the URL of your Heroku app. You can open this URL in your browser to view your Flask application. There is however an error. You can view the logs from the Heroku dashboard or the cli using the command:
heroku logs --tail
This will show you the details of the deployment process and any errors that occurred. You can use ChatGPT to troubleshoot the error and offer solutions by prompting the error logs.
-
Running the application locally using the command below should work fine:
python app.py
This will start the application locally, and you can view it in your browser.
-
To solve the error regarding gunicorn not installed, you can add gunicorn to the
requirements.txt
file by running the following command:pip install gunicorn pip freeze > requirements.txt
-
Push the changes to the Heroku remote repository. You can use the following command:
git add . git commit -m "Added gunicorn to requirements.txt" git push heroku main
This will push the changes to Heroku and rebuild the application.
-
Once the deployment is complete, you will see the URL of your Heroku app. You can open this URL in your browser to view your Flask application.
-
Congratulations! You have successfully deployed your Flask application to Heroku. You can now make changes to your Flask application and deploy them to Heroku by following the same steps. You can access your Flask application on Heroku by visiting the URL provided after the deployment is complete. You can share this URL with others to showcase your Flask application. Mine is here.
Happy Deploying! π