简体   繁体   中英

Load environment variables in python

Trying to load environment varibles in python module

import os
    
class Config(object):
    port = os.environ.get("PORT") or 5000
    
print(Config.port)
    
$ 5000

This is an easy fix for the problem I just experiences with flask

  • Create virtual environment using pip or pipenv ie virtualenv env
  • Activate the virtual environment source env/bin/acivate
  • Install python-dotenv module pip install python-dotenv

On top of your python file have something like this

In my .env file I have a variable named MY_VARIABLE

MY_VARIABLE=Somevalue

In my app.py I have this

import os

from dotenv import load_dotenv
# Loading up the values
load_dotenv()
class Config(object):
    port = os.environ.get("MY_VARIABLE") or 5000

print(Config.port)

Output

$ Somevalue

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM