Can not configure a Starlette .env file

Viewed 2560

I'm trying to set up the .env file for my project. But it seems incorrect.

I store the .env file in the same folder as the config.py file as below.

|__run.py
|___|myproject
    |__config.py
    |__.env

Code in my config.py file:

from starlette.config import Config
from starlette.datastructures import Secret, CommaSeparatedStrings
config = Config(".env")
BACKHUG_JWT_AES_KEY = config('BACKHUG_JWT_AES_KEY', default=None)

print(type(BACKHUG_JWT_AES_KEY))
print(BACKHUG_JWT_AES_KEY)

Data in the .env file:

BACKHUG_JWT_AES_KEY="SAMPLE_AES_KEY"

But the result I got was:

<class 'NoneType'>
None

I don't know why it got the None object. How can I fix it?

I run my project from a run.py file.

Code in the run.py file:

import uvicorn

if __name__ == "__main__":
    uvicorn.run("myproject.main:app", host="0.0.0.0", port=8888, reload=True)

3 Answers

There is a better way!

Use FastAPI and Pydantic for this. Pydantic provides a great BaseSettings class. Also, we have great documentation for settings and environment variables.

Create a Settings class by inheriting from Pydantic's BaseSettings:

from pydantic import BaseSettings

class Settings(BaseSettings):
    backhug_jwt_access_key: str

    class Config:
        env_file = "myproject/.env"

This Settings class automatically reads the variables from the .env file. Then from your main file you can use it like this:

from . import config
from functools import lru_cache

from fastapi import Depends, FastAPI

app = FastAPI()

@lru_cache()
def get_settings():
    return config.Settings()


@app.get("/info")
async def info(settings: config.Settings = Depends(get_settings)):
    return {"jwt_key": settings.backhug_jwt_access_key}

Remove the double quotes in the value and try again:

env file:

BACKHUG_JWT_AES_KEY=SAMPLE_AES_KEY

I'm pretty sure this is an issue with the current working directory. I can suggest two ways.

  • Move the .env file to one directory with the run.py file

Or

  • Change the path config = Config("myproject/.env")
Related