Flask is a lightweight framework for quick web application development in Python. This shot aims to teach you how to quickly bootstrap a basic app with it.
Let’s get started.
Note: For this exercise, make sure you have Python 3 installed on your computer.
mkdir flask101
<h2>move to the newly created folder</h2>
cd flask101
The virtual environment is important, as it helps avoid packages conflicts within your venv
module to create a lightweight virtual environment.
Now, within our project folder, let’s run the following.
python3 -m venv .venv
This will create the target directory (.venv
). This will house everything related to our virtual environment in the project, like the pyvenv.cfg
file, bin
: (or Scripts
in Windows), and lib
(or Lib
in Windows).
Notice that while my target directory is named
.venv
, you can name it as you wish.
The next step before we work on our project is to activate the corresponding environment.
<h2>GNU/Linx || MacOS</h2>
. venv/bin/activate
<h2>Windows</h2>
venv\Scripts\activate
Once you run the command above, your shell prompt will change to show the name of the activated environment; in our case, .venv
.
Note:
- If you want to quit the virtual environment, you need to type
deactivate.
- If running scripts is disabled on Windows due to the execution policy, open
Powershell
as administrator and run this command:Set-ExecutionPolicy Unrestricted
Type
Yes
(Y
) when it asks for confirmation.
Last but not least, you can now install our framework within the activated environment. To do so, use the following command.
pip install Flask
That is how you set up a working environment to work with Flask.
Let’s now learn how to say “Hello, world!” in Flask.
from flask import Flask
app = Flask(__name__)
@app.route("/")
def hello_world():
return "<p>Hello, World!</p>"
This code snippet is what a minimal Flask app looks like. We first import the Flask
class from the flask
module and then create an __name__
, a convenient shortcut for the name of the application’s module or package.
Next, we set a route (/
) to tell Flask what URL should trigger our function (hello_world()
). Our function returns the message we want to display in the user’s browser.
Warning: Do not call your application
flask.py
. This will conflict with Flask itself.
flask run
Running this command will throw an error. To fix it, we need to export the FLASK_APP
environment variable to tell our terminal which application to work with.
<h2>Bash</h2>
export FLASK_APP=hello
<h2>CMD</h2>
set FLASK_APP=hello
Now, we can run our app and enjoy the result on the browser:
flask run
* Running on http://127.0.0.1:5000/
Our application responds on the port
5000
ofhttp://localhost
.
Happy coding!