Python: Handling environment variables
This documentation is part of the Creating a REST API guide. View the full guide here: Step-by-step guide to building a REST API with Flask in Python.
👋 Welcome to the Stackhero documentation!
Stackhero provides a ready-to-use Python cloud solution designed to streamline your deployment process:
- Deploy your application to production in seconds with a simple
git push.- Use your own domain name, with automatic HTTPS certificate configuration for secure connections handled for you.
- Rely on automatic backups, one-click updates, and predictable pricing, so you can focus on your code, not infrastructure management.
- Benefit from strong performance and security on a private, dedicated infrastructure. Your environment is isolated and protected.
Save time and simplify your workflow: you can have your code running with Stackhero's Python cloud hosting in just 5 minutes.
Environment variables help you protect secrets like database credentials or API keys. Using them keeps sensitive data out of your codebase and Git history, and makes it easy to use different settings for each environment.
To manage environment variables, you can use the python-dotenv module. If you skipped the earlier install step, you can install it now:
pip install python-dotenv
pip freeze > requirements.txt
Create a .env file at your project root 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.