Flask is a micro web framework. It means that it is lightweight and extensible. By no means, Flask lacks in functionality due to its 'micro' nature.
To create a basic Flask application, you have to go through the following steps:
-
Set up a Python virtual environment in your project directory.
There are a lot of options here. I use the built-in module
venv
. In order to activate it you need to execute next commands:
$ python3 -m venv venv $ source venv/bin/activate
Once you're done, execute this to deactivate your virtual environment.
$ deactivate
Install Flask in this virtual environment with:
python3 -m pip install flask
Create a python file for your application. I usually call it
server.py
.-
Flask uses special environment variables
FLASK_APP
andFLASK_ENV
when you start a flask application.-
FLASK_APP
should be assigned to the name of the file that Flask should run. In our case, it isserver.py
that we've just created. -
FLASK_ENV
is used to toggle the Debug mode for the Flask app.
To set up those execute following commands in your shell:
$ export FLASK_APP=server.py $ export FLASK_ENV=development
-
-
We are ready to create our first Flask app! In the
server.py
add the following:
from flask import Flask app = Flask(__name__)
In this code snippet, we imported the Flask class, which represents a flask application. On the second line, we create an instance of that class and pass the
__name__
variable to it.__name__
is assigned to the string__main__
if the python module is executed, otherwise, it is assigned to the name of a module if it is imported. -
Then add the following function definition to your flask app:
@app.route('/') def index(): return 'Hello, World!'
Here we use the decorator
@app.route('/')
(decorator is a way of adding functionality to a function without altering that function implementation) to bind the specified URL with the function that should get called once the user tries to access that URL. In our case, we add a base URL/
and bind it to the functionindex
, which will return a stringHello, World!
. -
In order to run this application, execute the following command:
$ flask run
In your browser, go to the
127.0.0.1:5000
, and if you have set up everything correctly, you will be able to seeHello, World!
in your browser window.
In the next blog post, I will cover how to use HTML templates and template inheritance using the Jinja templating engine, to utilize the fundamental principle of software design, the DRY principle. Stay tuned!
Top comments (2)
Hi Mariia,
Awesome, you might get me started to explore Flask
Thank you very much!