digitros / nextjs-fastapi

https://nextjs-fastapi-starter.vercel.app
MIT License
407 stars 117 forks source link

Reading Vercel Environment Variables in Python #6

Open knnhcn opened 1 year ago

knnhcn commented 1 year ago

How can I read Environment Variables defined in Vercel e.g. when running in production?

knnhcn commented 1 year ago

Also in development?

knnhcn commented 1 year ago

After some research and trials I found a way to use .env variables in Python code. However, there are some additional steps required to do so:

First, add python-dotenv to your requirements.txt:

fastapi==0.95.2
uvicorn[standard]
python-dotenv

Then, in your index.py, load the .env file:

from dotenv import load_dotenv
load_dotenv()

Finally, you can use your keys defined in .env like below:

os.getenv("MY_KEY")

This also worked in production when deployed to Vercel and variables defined in Vercel Environment Variables.

digitros commented 1 year ago

You can also install python-decouple for that.

fastapi
uvicorn[standard]
python-decouple

Then, when you want to use an environment variable, you can use:

from decouple import config
ENVIRONMENT_VARIABLE = config("YOUR_ENVIRONMENT_VARIABLE")