PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Friday, August 19, 2022

[FIXED] How to set environment variable based on development or production in FastAPI?

 August 19, 2022     development-environment, environment-variables, fastapi, production-environment, python     No comments   

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.

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)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing