Flask Tutorials: Environment Variables šŸŽÆ

beginner
14 min

Flask Tutorials: Environment Variables šŸŽÆ

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. 🐳

What are Environment Variables? šŸ“

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.

Why Use Environment Variables? šŸ’”

  • Security: Keeping sensitive information like API keys as environment variables helps protect your code from being exposed.
  • Configuration Flexibility: You can easily change settings, such as database connections or third-party service credentials, without modifying your code.

Setting Environment Variables šŸ“

Flask applications can be run with environment variables by setting them in your system's environment or within your Flask application itself.

System Environment Variables šŸ“

On Unix-based systems like Linux and macOS, you can set environment variables using the export command:

bash
export MY_VARIABLE=my_value

On Windows, use the set command:

cmd
set MY_VARIABLE=my_value

Flask Application Environment Variables šŸ“

Flask provides a Flask.config object where you can store configuration settings, including environment variables.

python
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'].

Accessing Environment Variables šŸ“

To access environment variables, you can use the os module in Python.

python
import os my_variable = os.getenv('MY_VARIABLE')

Practical Example šŸ“

Let's create a Flask app that retrieves data from an API using an API key stored as an environment variable.

python
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()

Quiz šŸŽÆ

Quick Quiz
Question 1 of 1

How can you access an environment variable named `MY_VARIABLE` in a Flask application?