0

I am working on a Python API project on the Glitch platform and I didn't find anything on how to reference the .env file and use the variables in a python script. os.environ will not work because I haven't imported anything to the app. How should I reference it properly and how should I import the module correctly?

import os
var = os.environ['SECRET_NAME']  # Will raise a KeyError if not existed
var2 = os.environ.get('SECRET_NAME')  # Will give a value of 'None" if not existed 
jonrsharpe
  • 115,751
  • 26
  • 228
  • 437
  • process.env is how you access env vars in *JavaScript*. If you're asking how to access env vars in Python, have you tried researching that? – jonrsharpe Jun 06 '20 at 22:43
  • @jonrsharpe yes, I searched everywhere on how to refrence .env in a python script – Parsa Showkati Jun 06 '20 at 22:48
  • https://stackoverflow.com/questions/4906977/how-to-access-environment-variable-values? https://pypi.org/project/python-dotenv/? – jonrsharpe Jun 06 '20 at 22:53

1 Answers1

0

Use code below to access environment variables from .env file.

python-dotenv documentation

import os
from os.path import join, dirname
from dotenv import load_dotenv

dotenv_path = join(dirname(__file__), '.env')
load_dotenv(dotenv_path)

SECRET_NAME = os.environ.get("SECRET_NAME")

Ahmed ElMetwally
  • 2,276
  • 3
  • 10
  • 15