encode / uvicorn

An ASGI web server, for Python. 🦄
https://www.uvicorn.org/
BSD 3-Clause "New" or "Revised" License
8.41k stars 728 forks source link

`uvicorn.run` `env_file` Not Passed Correctly #2340

Closed oliv10 closed 4 months ago

oliv10 commented 4 months ago

Initial Checks

Discussion Link

https://github.com/encode/uvicorn/discussions/2328

Description

When passing a .env file with the uvicorn.run command it does not properly pass its information on to the uvicorn and FastAPI application.

Example Code

### Test Code

import uvicorn
import fastapi
from pydantic_settings import BaseSettings
import argparse
import logging
from logging import getLogger

class Settings(BaseSettings):
    DEBUG: bool = False

SETTINGS = Settings()
app = fastapi.FastAPI()

Logger = getLogger("uvicorn")
if SETTINGS.DEBUG:
    Logger.setLevel(logging.DEBUG)
    Logger.debug("Debug Mode Enabled")
else:
    Logger.setLevel(logging.INFO)

@app.get("/")
async def root():
    if SETTINGS.DEBUG:
        return {"message": "DEBUG World"}
    else:
        return {"message": "Hello World"}

if __name__ == "__main__":
    parser = argparse.ArgumentParser()
    parser.add_argument("--env-file", type=str, default=".env")
    args = parser.parse_args()

    uvicorn.run(app, env_file=args.env_file)

.env file

DEBUG=True

Test Cases

Incorrect Output

python3 ./test_uvicorn.py

INFO:     Loading environment from '.env'
INFO:     Started server process [279760]
INFO:     Waiting for application startup.
INFO:     Application startup complete.
INFO:     Uvicorn running on http://127.0.0.1:8000 (Press CTRL+C to quit)
INFO:     127.0.0.1:40028 - "GET / HTTP/1.1" 200 OK

Correct Output

uvicorn test_uvicorn:app --env-file .env

INFO:     Loading environment from '.env'
DEBUG:    Debug Mode Enabled
INFO:     Started server process [280032]
INFO:     Waiting for application startup.
INFO:     Application startup complete.
INFO:     Uvicorn running on http://127.0.0.1:8000 (Press CTRL+C to quit)
DEBUG:    DEBUG
INFO:     127.0.0.1:60288 - "GET / HTTP/1.1" 200 OK

Python, Uvicorn & OS Version

Running uvicorn 0.29.0 with CPython 3.12.2 on Linux

[!IMPORTANT]

  • We're using Polar.sh so you can upvote and help fund this issue.
  • We receive the funding once the issue is completed & confirmed by you.
  • Thank you in advance for helping prioritize & fund our backlog.

Fund with Polar