Getting Started with Flask Development
A Beginner's guide to getting started with Flask.
Introduction
In this article, I explain how to install Flask on your computer to develop web applications if you’re already familiar with Python programming. In Flask you can create web applications with Python and a little HTML and CSS. I’m explaining step by step process so that you can follow along with me. I’m using a Mac computer for this tutorial.
1. Setting up the platform.
First, you need to have pip
installed on your computer to get the necessary things installed when developing with Flask. Check whether you have pip
in your computer using thepip --version
command. If you don’t have pip
installed on your computer, use the below commands and install pip
into your local workstation.
$ curl https://bootstrap.pypa.io/get-pip.py -o get-pip.py $ python get-pip.py $ pip --version
Once you’ve got pip
installed on your computer, you’re almost ready to get started. Specially, you can install Flask globally as well as inside a virtual environment. In this tutorial, I install Flask inside a virtual environment and run our first Flask App.
You can check whether you have already installed Flask on your system via pip list
command. If you don't find Flask in the list, run the pip install flask
command to install Flask. As I mentioned earlier since we run Flask inside a virtual environment, you don’t need to install Flask globally.
2. Create the first Flask App
Next, check whether you have virtualenv
is installed on your system using the pip list
command. If not, use pip install virtualenv
command. This will help you to run the app in a virtual environment.
Then navigate to your project directory and run the virtualenv env
command in the terminal. This will create a env
directory inside your project directory. After that, you need to activate the env
using the source env/bin/activate
or . env/bin/activate
command[this command varies if you’re using a windows computer]. Now you’re inside the virtual environment.
Check pip list
and see what you have got there. You will not see Flask in the list even though you have previously installed it globally. Then, you can install the Flask
inside the virtual environment using pip install flask
and it won't affect globally.
Next, create an app.py
file and add the following code into it.
from flask import Flask
app = Flask(__name__)
@app.route('/')
def index():
return '<h1>Hello from Flask!</h1>'
if __name__ == '__main__':
app.run(debug=True)
Then you can run the flask run
command on your terminal to start Flask App
and navigate to 127.0.0.1:5000
to open the app in the browser.
If you don’t use the name app.py
as the file name, you need to set the environment variable to the relevant file using the .flaskenv
file. Suppose your file name is main.py
. Then you need to create the .flaskenv
file and set these variables as follows.
FLASK_ENV=development
FLASK_APP=main.py
Now, since you have the .flaskenv
file you need to run pip install python-dotenv
command before running the flask run
command. This command will allow you to use the .flaskenv
file. Once you run the pip install python-dotenv
command then run the deactivate
command to disable the environment and once again activate the virtual environment using the source env/bin/activate
command. Then run the flask run
command to start the app and see the output in the browser.
In addition, you can save all your packages into a text file and one day if you have to move your project to a different computer you don’t have to create the env
directory once again. You can use this text file to create it. Use the below command to add your packages to the text file.
$ pip freeze > requirements.txt'requirements.txt' is the file name
Then in the new machine, you can run the below command to create env
folder using the text file.
$ pip install -r requirements.txt
3. Render web pages and add routes
Then create templates
, static
and images
directories inside the project directory. These directories hold HTML pages, style sheets and pictures respectively. After that, create index.html
file inside the templates directory and CSS directory inside the static directory. You can also add the main.css file inside the CSS directory.
Also, you need to import the render_template
module into the app.py
in order to render HTML pages.
Then you can run the flask run
command to render the index.html
file on the browser.
A web application generally has routes to make it easier to explore for the users. At the moment we have a single HTML page and static content. Next, we will see how to add multiple pages and set routes in the Flask app.
Let’s create two HTML files called about.html
and contact.html
. Make sure you also place these two files inside the templates
directory. For learning purposes, I create these two files as simple as it is.
Next, we can add routes into our app.py
file as below.
Once you run the flask run
command you will see these pages and navigations on the browser.
4. Template Inheritance
Template Inheritance is a fascinating feature that you meet when developing apps with Flask. Basically, what template inheritance does is, it allows us to create a base or layout for all our HTML web pages and customize/add only the relevant part(s) without building the entire HTML web page from scratch over and over again.
To achieve template inheritance in our Flask app, we create a base.html
file and extends
it into the other HTML files as below. This scenario Jinja2
comes into play and those delimiters belong toJinja2
. Generally, Jinja2
is known as a modern templating language for Python developers to create HTML, XML or other markup formats.
When you run the command pip list
, you will see Jinja2
is already there and it has been installed with Flask.
Let’s create our base.html
file as a normal HTML file and add Jinja2
delimiters where necessary.
Here, {% block head %}{% endblock%}
and {% block body %}{% endblock%}
are Jinja2
delimiters.
Next, let’s modify our index
, about
and contact
HTML files accordingly.
This method is so easy to apply and create dynamic content on our web pages. Next, will see how to add and render dynamic content in our app.
5. Rendering Dynamic Content.
Let’s create a simple Python list in app.py
file and add the necessary changes into it as below.
And add the necessary changes into index.html
as follows.
Likewise, You can loop through a list or dictionary and pass values to your HTML page from the Python app.
6. Working with the GET, POST Methods
Generally, we have forms on our web pages to get the user input and take necessary actions according to that. So, in this section, you will learn how to get user inputs from the web page and pass it to our app.
Let’s create a new page called login.html
file as follows.
Let’s update the app.py
app to handle the form requests. This time we import 4 new modules to the app.py
file which are request
, redirect
, url_for
and flash
.
To handle GET, POST
requests in Flask you need to have the key. In the above app.py
code snippet, I’ve set that key into the app.config[‘SECRET_KEY’]
. You can generate a key for your app as below.
Open another tab of the terminal and run the command $ python
. This opens the Python shell and then runs the below commands.
$ python>>> import secrets
>>> secrets.token_hex(16)
'de921e121eec1e95642035ca4d39d34b'
>>>
Copy the value and set it to the app.config['SECRET_KEY']
.
Then once the user filled out the form and clicks the Log In
button, the results will be displayed on success.html
file. So, Let’s create the success.html
file as follows.
Finally, You will get the output on your browser.
Here’re the app snapshots.
Congratulations
Hope you liked and enjoyed the post and hope you find the information useful. This is a beginner-friendly tutorial for those who like to Develop Web Apps using Python-related frameworks.
If you have any questions, please drop me a message.
Thank you for reading!
> Stay tuned for more posts related to Python and Flask ✌️<
Happy Coding! 👨🏻💻