In this tutorial, we will learn how to manage environment variables in a production setting using Flask. Environment variables are an important aspect of web applications that securely store configuration settings.
By the end of the tutorial, you will be able to:
- Understand what environment variables are
- Use environment variables in Flask applications
- Manage environment variables in a production environment
Environment variables are key-value pairs that are used to customize the system environment for your application. They can be used to store sensitive data like API keys, passwords, and other configuration settings.
In Flask, the configuration settings are typically stored in files, but in a production environment, it's more secure and scalable to use environment variables.
In a Unix-based system, you can set an environment variable using the export
command as follows:
export VARIABLE_NAME="Variable Value"
In Windows, you can use the set
command:
set VARIABLE_NAME="Variable Value"
In Flask, you can access these variables using os.environ
or Flask's config
object. For instance:
import os
from flask import Flask
app = Flask(__name__)
app.config['SECRET_KEY'] = os.environ.get('SECRET_KEY')
os.environ
import os
from flask import Flask
app = Flask(__name__)
app.config['SECRET_KEY'] = os.environ.get('SECRET_KEY')
In this example, we're using os.environ.get('SECRET_KEY')
to get the value of the SECRET_KEY
environment variable that we've set in our system.
config.from_pyfile
from flask import Flask
app = Flask(__name__)
app.config.from_pyfile('config.py')
In this example, we're loading the configuration from a Python file named config.py
. This file contains the environment variables.
In this tutorial, we've learned what environment variables are, how to set them in our system, and how to use them in a Flask application. Our next step would be to learn how to manage these variables in a production environment, which involves different strategies and tools like Docker, Kubernetes, or cloud services.
DATABASE_URL
with the value of your choice, then access it in a Flask application.config.py
file, then load it using Flask's config.from_pyfile
method.# Set the environment variable
export DATABASE_URL="sqlite:///site.db"
# Access it in Flask
import os
from flask import Flask
app = Flask(__name__)
app.config['DATABASE_URL'] = os.environ.get('DATABASE_URL')
# config.py
SECRET_KEY = 'your-secret-key'
DATABASE_URL = 'sqlite:///site.db'
# Flask application
from flask import Flask
app = Flask(__name__)
app.config.from_pyfile('config.py')
In these exercises, you practiced setting and using environment variables in Flask. For further practice, try exploring different ways to manage these variables in a production environment.