Flask supports multiple environments: development, testing and production. In this article you learn how to set the environment you want.
If you worked in software development jobs before, you may already be familiar with these.
Related course: Python Flask: Create Web Apps with Flask
Set environment
Types of environments
There is an important concept that needs our attention, which is that every configuration file is environment-related, that is, because there are multiple environments, multiple configurations are present.
If you don’t understand the meaning of this sentence, let’s look at the file names under the config directory, which can actually be divided into several categories:
development: a development environment that generally uses for local development environments
product: production environments for online deployment
testing: for test environments, general for various test uses
As we can see, we have a local environment in which we can develop debugging locally.
After you have tested it (in the testing environment) and completed of the tests, there will be an production environment.
Set environment
The mystery here is in the config/init.py file. Let’s take a look at this file:
1 | # coding: UTF-8 |
In the config/init.py
file, I define a load_config()
function that accepts a mode parameter representing the configuration of what environment.
If this parameter is not passed, the MODE
environment variable in the system environment variable is used by default, and then the specified configuration file is returned according to the specified environment.
If you do not have a specified configuration file, you can only return the default environment variable.
Similarly, if you need to add a custom environment configuration file, you need to simply modify the function, and specify that you can load the configuration files that you customize.
After you use the configuration load configuration to resolve this problem, next is using these configurations in our Flask application.
Because load_config()
is all configured, the use is also not a big problem, here is an example:
1 | """Create Flask app.""" |
The configuration is set using the config from_object()
setting for the Flask object.It’s that simple.
Alternative
The above method works and is a good way to set an environment, but it’s not the only way.
By default if you start a Flask server, it is set to a certain environment mode.
This is displayed when you run the command flask example.py
.
1 | * Serving Flask app "example" (lazy loading) |
In this case:
1 | * Environment: production |
You can run the shell command
1 | export FLASK_ENV=development |
This changes the environment to
1 | * Environment: production |
You may want to set that in your .env
file.
Related course: Python Flask: Create Web Apps with Flask