Python / Uvicorn Fundamentals Interview Questions
What is the --app-dir flag in Uvicorn and when do you need it?
The --app-dir flag adds a specific directory to sys.path before Uvicorn tries to import the application. This is useful when your application module is not in the current working directory or the standard Python path.
# Project structure: # /project/ # src/ # myapp/ # main.py ← app lives here # Without --app-dir: run from /project/src/ cd /project/src uvicorn myapp.main:app # With --app-dir: run from /project/ cd /project uvicorn myapp.main:app --app-dir src # Equivalent to: PYTHONPATH=/project/src uvicorn myapp.main:app # Docker example - app in /app/src CMD ["uvicorn", "myapp.main:app", "--app-dir", "src", "--host", "0.0.0.0", "--port", "8000"] # Programmatic: uvicorn.run("myapp.main:app", app_dir="src") # Multiple app directories: use PYTHONPATH env var instead export PYTHONPATH=/project/src:/project/lib uvicorn myapp.main:app
Common use case: projects using a src/ layout (where application code lives in src/mypackage/ rather than the project root) need either --app-dir src or a proper package installation (pip install -e .). The --app-dir approach is simpler for containerised deployments where installation may be skipped.
More Related questions...