0

I want to add some global environment variables in my Python project. My thought was to add a .env in my project directory and set up some variables as follows:

URL='https://example.dev/api'
AUTHORIZATION='Basic QWERTYUIO234ERTY89IOKXCVB'

In Python, how would I be able to access those variables in my project. Online I've seen seen os.getenv('URL'), where os is also imported, but this doesn't seem to be working. Does anyone know how I might be able to do this? I could also set up an appSettings file to contain these global variables. Alternatively, if there's a better practice to use for Python, could someone please share?

ENV
  • 877
  • 2
  • 10
  • 32
  • 2
    Does this answer your question? [Reading in environment variables from an environment file](https://stackoverflow.com/questions/40216311/reading-in-environment-variables-from-an-environment-file) – Drdilyor Jun 01 '21 at 23:46

2 Answers2

1

You will need to include the package python-dotenv. This is the documentation for your reference.

For your case, you will need to do the following,

from dotenv import load_dotenv

load_dotenv()  # take environment variables from .env.

url = os.getenv('URL', 'default_url')
authorization = os.getenv('AUTHORIZATION', 'default_authorization')
Yeong Jong Lim
  • 208
  • 1
  • 4
  • You don't need this plus it puts a runtime dependency on something that may not be there when the project is run elsewhere. assuming that .env is just being set for use in VS Code. – LhasaDad Jun 01 '21 at 23:45
0

Most likely you forgot to set the following setting in to point at the .env file: python.envFile

LhasaDad
  • 1,786
  • 1
  • 12
  • 19