Welcome to our comprehensive guide on using Environment Variables in Flask! This tutorial is designed for beginners and intermediates, so let's dive right in. š³
Environment variables are values that can be set to store configuration information for your Flask application. They are useful because they can be easily changed without modifying your code.
Flask applications can be run with environment variables by setting them in your system's environment or within your Flask application itself.
On Unix-based systems like Linux and macOS, you can set environment variables using the export command:
export MY_VARIABLE=my_valueOn Windows, use the set command:
set MY_VARIABLE=my_valueFlask provides a Flask.config object where you can store configuration settings, including environment variables.
from flask import Flask
app = Flask(__name__)
app.config['MY_VARIABLE'] = 'my_value'š” Pro Tip: You can access environment variables within your Flask application using app.config['KEY'].
To access environment variables, you can use the os module in Python.
import os
my_variable = os.getenv('MY_VARIABLE')Let's create a Flask app that retrieves data from an API using an API key stored as an environment variable.
import os
import requests
from flask import Flask, jsonify
app = Flask(__name__)
app.config['API_KEY'] = os.getenv('API_KEY')
@app.route('/api_data')
def api_data():
if not app.config['API_KEY']:
return 'Missing API Key', 500
api_url = f'https://api.example.com/data?key={app.config["API_KEY"]}'
response = requests.get(api_url)
if response.status_code == 200:
data = response.json()
return jsonify(data)
else:
return 'Error fetching data', 500
if __name__ == '__main__':
app.run()How can you access an environment variable named `MY_VARIABLE` in a Flask application?