Skip to content

Commit

Permalink
Fix static file handling on localhost
Browse files Browse the repository at this point in the history
Note: this does not apply to production because we serve static files from Nginx there: those static file requests never make it to the Django application and, indeed, it is not configured to serve static files. This change uses the ASGI static file handler that the Django `runserver` management command uses and correctly handles streaming responses. The only consequence of not doing this is that warnings will appear locally and, if for some reason local interactions are bypassing the static file cache on the browser, you could get a memory leak. Again, that only applies to local environments. Python code never interacts with, considers, or is configured for static files in production, so this is not an issue for production. The correct behaviour for production, which you can test by setting ENVIRONMENT to something other than `local` in `api/.env`, is to 404 on static files.
  • Loading branch information
sarayourfriend committed Nov 2, 2023
1 parent d4a7956 commit 17802db
Show file tree
Hide file tree
Showing 3 changed files with 12 additions and 5 deletions.
6 changes: 6 additions & 0 deletions api/conf/asgi.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,8 @@
import os

import django
from django.conf import settings
from django.contrib.staticfiles.handlers import ASGIStaticFilesHandler

from conf.asgi_handler import OpenverseASGIHandler

Expand All @@ -14,3 +16,7 @@ def get_asgi_application():


application = get_asgi_application()


if settings.ENVIRONMENT == "local":
static_files_application = ASGIStaticFilesHandler(application)
3 changes: 0 additions & 3 deletions api/conf/urls/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -43,6 +43,3 @@
),
),
]

if settings.ENVIRONMENT == "local":
urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)
8 changes: 6 additions & 2 deletions api/run.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,12 +4,16 @@


if __name__ == "__main__":
is_local = os.getenv("ENVIRONMENT") == "local"

app = "conf.asgi:static_files_application" if is_local else "conf.asgi:application"

uvicorn.run(
"conf.asgi:application",
app,
host="0.0.0.0",
port=8000,
workers=1,
reload=os.getenv("ENVIRONMENT") == "local",
reload=is_local,
log_level="debug",
log_config={
"version": 1,
Expand Down

0 comments on commit 17802db

Please sign in to comment.