Application Setup
Flask apps can take many different forms but once they go beyond one or two pages it’s a good idea to structure them properly. As we know the blog will be several different pages with different functionality it will be setup for this from the start. We also will want automated tests so we will add the base for that as well.
What does this all mean?
-
The
create_app
function is the application factory which means its a function that will create our application (similar to a factory). -
The
app = Flask(__name__, instance_relative_config=True)
creates the Flask instance with__name__
being the current module name (flaskapp
) andinstance_relative_config=True
tells Flask that configuration files are relative to the instance folder. The instance folder is located outside the flaskapp package and can hold local data that shouldn’t be committed to version control, such as configuration secrets and the database file. It also means we don’t have to worry about where certain things are stored which makes testing a lot easier. -
app.config.from_mapping
is used for the core config of our app, we have a secret keyDEV
and a database location. The secret key is used to keep the client-side sessions secure. The database location is where the database will be stored.
-
As we know that automated tests are going to be used we add the ability for the tests to override some settings so that it can be tested properly and not break our app.
-
with contextlib.suppress(OSError):
is used to suppress the error if the instance folder already exists. This is because we don’t want to overwrite anything that is already there. -
To make sure our application works we create a simple route that returns “Hello, World!” that can be accessed at
/hello
.
Running our Application
You’ll see output similar to this:
Visit http://127.0.0.1:5000/hello in a browser and you should see the “Hello, World!” message. Congratulations, you’re now running your Flask web application!
If another program is already using port 5000, you’ll see OSError: [Errno 98]
or OSError: [WinError 10013]
when the server tries to start. See Address already in use for how to handle that.