Python: Handling environment variables
This documentation is part of the Creating a REST API guide. You can view the complete guide here: How to create a REST API using Flask.
👋 Welcome to the Stackhero documentation!
Stackhero offers a ready-to-use Python cloud solution that provides a host of benefits, including:
- Deploy your application in seconds with a simple
git push.- Use your own domain name and benefit from the automatic configuration of HTTPS certificates for enhanced security.
- Enjoy peace of mind with automatic backups, one-click updates, and straightforward, transparent, and predictable pricing.
- Get optimal performance and robust security thanks to a private and dedicated VM.
Save time and simplify your life: it only takes 5 minutes to try Stackhero's Python cloud hosting solution!
Environment variables are vital for protecting sensitive information, such as database credentials or API keys. There are two main benefits to using environment variables:
- Your secrets are not stored in your Git repository, ensuring unauthorised individuals cannot access your sensitive data even if they gain access to your source code.
- You can use different credentials for different environments (for example, production versus development).
To manage environment variables, we use the python-dotenv module. First, install it if you haven't already:
pip install python-dotenv
pip freeze > requirements.txt
Next, create a .env file at the root of your project and add your development environment variables. For example:
ENV="development"
DATABASE_PASSWORD="secretPassword"
THIRD_API_PRIVATE_KEY="secretKey"
Finally, add the .env file to your .gitignore to maintain security:
echo ".env" >> .gitignore
To access these environment variables in Python, simply use os.environ.get():
import os
print(os.environ.get('ENV'))
The
.envfile is used only for the development environment. For staging or production, set the environment variables on the Stackhero dashboard in your Python service configuration.