Python: Managing environment variables
This documentation is part of the Creating a REST API guide. You can view the complete guide here: Step-by-step guide to building a REST API with Flask in Python.
👋 Welcome to the Stackhero documentation!
Stackhero offers a ready-to-use Python cloud solution designed to simplify your deployments:
- Deploy your application to production within seconds using a simple
git push.- Use your own domain name, with automatic HTTPS certificate setup for secure connections managed on your behalf.
- Take advantage of automatic backups, one-click updates, and predictable pricing, so you can focus on your code rather than infrastructure management.
- Benefit from high performance and security on a private, dedicated infrastructure. Your environment is isolated and protected.
Save time and streamline your workflow: your code can be up and running with Stackhero's Python cloud hosting in just 5 minutes.
Environment variables help you protect secrets such as database credentials or API keys. Using them keeps sensitive data out of your codebase and Git history, and makes it easier to use different settings for each environment.
To manage environment variables, you can use the python-dotenv module. If you skipped the earlier installation step, you can install it now:
pip install python-dotenv
pip freeze > requirements.txt
Create a .env file at the root of your project and add your development environment variables:
ENV="development"
DATABASE_PASSWORD="secretPassword"
THIRD_API_PRIVATE_KEY="secretKey"
Add .env to your .gitignore so it is not committed to Git:
echo ".env" >> .gitignore
You can access these variables in Python using os.environ.get():
import os
print(os.environ.get('ENV'))
The
.envfile is for development only. For production or staging, you can set environment variables directly in your Stackhero dashboard under your Python service configuration.