Issue
I want to have different environment variables based on development and production but i can't seem to find anything related to this topic for FastAPI.
Is it possible that i can have .env, .env.local, .env.prod to have different environment variables
Solution
I don't think you need multiple files. Usually how it's done is, have a single config file that has the default values, usually this is your "local" config file. For prod, staging and other environments, you can override these settings by setting environment variables, most hosts support it nowadays. It's more secure and you don't have to expose production secrets and keys in your repository.
This library is one example of what you code use: https://github.com/theskumar/python-dotenv
EDIT
For example, if your application is hosted in Heroku, the heroku config
commands of the Heroku CLI makes it easy to manage your app’s config vars:
heroku config:set SOME_CONFIG_I_NEED=value for production
You can also edit config vars from your app’s Settings tab in the Heroku Dashboard.
Please refer to the Heroku documentation for more information.
After you set the env vars in Heroku, this is how you would access them from your Python code (using python-dotenv):
First, install python-dotenv
:
pip install python-dotenv
Now, create a file called .env
in the root of your project with the following contents:
# Development settings
SOME_CONFIG_I_NEED=value for development
Now in your python file:
from dotenv import load_dotenv
load_dotenv() # take environment variables from .env.
SOME_CONFIG_I_NEED = os.environ.get("SOME_CONFIG_I_NEED")
print(SOME_CONFIG_I_NEED) # This will print "value for development" when running on local, and will print "value for production" when running in Heroku.
Answered By - AndreFeijo Answer Checked By - Mary Flores (PHPFixing Volunteer)
0 Comments:
Post a Comment
Note: Only a member of this blog may post a comment.