Virtual environment
You have to use a virtual environment to manage the dependencies for your project.
Virtual environments are independent groups of Python libraries, one for each project. Packages installed for one project will not affect other projects.
Python 3 is bundled with the venv module to create virtual environments.
Create an environment
Create a new folder and a venv folder within:
$ mkdir pyflask $ cd pyflask $ python3 -m venv venv
Windows:
$ py -3 -m venv venv
Activate the environment
Activate the corresponding environment:
$ source venv/bin/activate
Windows:
> venv\Scripts\activate
Install Flask
Within the activated environment install Flask:
$ pip3 install Flask
Create an applcation
In the earlier created pyflask folder create a file “app.py” and write the code below:
from flask import Flask app = Flask(__name__) @app.route("/") def index (): return "Hello World!" if __name__ == "__main__": app.run(debug=True)
To run the application you can either use the flask command or python’s -m
switch with Flask. Before you can do that you need to tell your terminal the application to work with by exporting the FLASK_APP
environment variable:
$ export FLASK_APP=app.py
$ flask run
Or
$ export FLASK_APP=app.py
$ python -m flask run
In your browser open https://127.0.0.1:5000/ to see your project running:
Templates
Templates are a good way to have separated web pages. This way you can add your own html templates.
Create a new file called “index.html” and use this code:
<html> <body> Hi! Index template here! </body> </html>
In your script change following:
from flask import Flask from flask import render_template app = Flask(__name__) @app.route("/") def index (): return render_template("index.html") if __name__ == "__main__": app.run(debug=True)