Flask is a Python microframework for building web applications and APIs – its simple architecture allows you to get running in seconds.
In this shot, you will learn how to create a Flask app that displays hello-world.
Click the run button below to activate the terminal. After the default commands in the terminal get executed, run these commands in the terminal.
python3 -m venv venv
. venv/bin/activate
Note: If running locally, you may need to install venv
. Run the command below to install venv.
$ python3 -m venv venv # unix
$ py -3 -m venv venv # windows
Run the widget below and install Flask into the virtual environment using:
pip install Flask
The widget contains an app.py
file. This file:
Flask
class from the flask
package. Flask is used to create instances of web applications.Flask
.app.py
.from flask import Flask app = Flask(__name__) @app.route('/') def hello_world(): return 'Hello, World!' if __name__ == "__main__": app.run()
A Flask application has a single entry point. For the terminal to know the entry point of your app, you need to set a FLASK_APP
environment variable. These commands have already been set in the widget below, simply run the widget and check the output tab.
export FLASK_APP=app.py
Now, run your flask app using:
flask run
from flask import Flask app = Flask(__name__) @app.route('/') def hello_world(): return 'Hello, World!' if __name__ == "__main__": app.run()
__name__ == "__main__"
mean?The conditional check if __name__ == "__main__"
simply checks if the script being executed is app.py
.
Say you created a script called utils.py
that only contains print(__name__)
. If you import utils.py
into app.py
and run app.py
, the print statement from utils.py
will output utils
, which is the name of the file.
In the case of app.py
the name variable will be “main”.
Flask allows you to set up a web application with minimal configuration. These applications range from Model-View-Controller (MVC) apps to APIs.
In this shot, you learned how to set up a web application using the Flask framework.
RELATED TAGS
CONTRIBUTOR