A package in Python
This time we are gonna create a package (more files in a folder). We give ‘blog’ as name of the folder with our site. Into the blog we put three files (plus another):
- blog:
- __init__.py
- routes.py
- run.py
- .flaskenv
The __init__.py file (the __ are two underscore, called dunder as double underscore) is needed to make Python know that the folder is a package. Let’s see what we will put into the three filese to start. As blog now becomes the name of the package, we can import functions and istances from it, as you can see in the code below.
The __init__.py file code:
from flask import Flask app = Flask(__name__) from blog import routes
The routes.py code:
from blog import app @app.route("/") def homepage(): return "<h1>Homepage of my blog</h1>"
the run.py code
from blog import app
the .flaskenv script
To avoid to write everytime we start the terminal what’s in the following script, we save the script into the .flaskenv file, after we installed a module with pip install python-dotenv.
FLASK_APP=run.py FLASK_ENV=development
The vs studio setup with the pip install python-dotenv to avoid having to set the FLASK_APP every time you start the terminal.