Replies: 3 comments
-
Beta Was this translation helpful? Give feedback.
-
I faced similar problem trying to debug my FastAPI project. When uvicorn server is launched like this:
with specified After some time trying to fix it, I have found the culprit. I think if terminal session has environment variables uvicorn will use them regardless of specified .env file. So after changing the .env file, restarting of terminal is required to load new values. |
Beta Was this translation helpful? Give feedback.
-
I know it's a bit late to answer but leaving it for whom may ran into the same problem. The problem is that the class Settings(BaseSettings):
DEBUG: bool = False
SETTINGS = Settings()
app = fastapi.FastAPI() Uvicorn loads the env file here, inside the To solve this problem you need to wrap the settings variable into a function. def get_settings():
return Settings() Then, call it when it's obviously after @app.get("/")
async def root():
# this is invoked when the http requests arrive here.
# thus, this can not be invoked before the server started to run.
if get_settings().DEBUG:
return {"message": "DEBUG World"}
else:
return {"message": "Hello World"} Even better with dependency injection. from fastapi import Depends
from typing_extensions import Annotated
AppSettings = Annotated[config.Settings, Depends(get_settings)]
@app.get("/")
async def root(settings: AppSettings):
if settings.DEBUG:
return {"message": "DEBUG World"}
else:
return {"message": "Hello World"} |
Beta Was this translation helpful? Give feedback.
Uh oh!
There was an error while loading. Please reload this page.
Uh oh!
There was an error while loading. Please reload this page.
-
Initial Checks
Discussion Link
Description
When passing a
.env
file with theuvicorn.run
command it does not properly pass its information on to the uvicorn and FastAPI application.Example Code
.env file
Test Cases
Incorrect Output
Correct Output
Python, Uvicorn & OS Version
Important
Beta Was this translation helpful? Give feedback.
All reactions