[英]django dev server, adding headers to static files
使用 django 開發服務器 (1.7.4),我想向它提供的所有靜態文件添加一些標頭。
看起來我可以將自定義視圖傳遞給django.conf.urls.static.static
,如下所示:
if settings.DEBUG:
from django.conf.urls.static import static
from common.views.static import serve
urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
urlpatterns += static(settings.STATIC_URL,
document_root=settings.STATIC_ROOT, view=serve)
而common.views.static.serve
看起來像這樣:
from django.views.static import serve as static_serve
def serve(request, path, document_root=None, show_indexes=False):
"""
An override to `django.views.static.serve` that will allow us to add our
own headers for development.
Like `django.views.static.serve`, this should only ever be used in
development, and never in production.
"""
response = static_serve(request, path, document_root=document_root,
show_indexes=show_indexes)
response['Access-Control-Allow-Origin'] = '*'
return response
但是,簡單地在INSTALLED_APPS
使用django.contrib.staticfiles
會自動添加靜態 url,並且似乎沒有辦法覆蓋它們。 從INSTALLED_APPS
刪除django.contrib.staticfiles
可以完成這項工作,但是,如果我這樣做,靜態文件模板標簽將不再可用。
如何使用 django 開發服務器覆蓋為靜態文件提供的標頭?
staticfiles
應用程序覆蓋核心runserver
命令,但允許您禁用靜態文件的自動服務:
python manage.py runserver --nostatic
我發現作者的代碼對我不起作用,我會得到如下錯誤:
[10/Dec/2020 18:08:13] "GET /static/img/foo.svg HTTP/1.1" 404 10482
Not Found: /static/img/foo.svg
如果這有所作為,我正在使用 Django 3。
這就是我所做的:
from django.contrib.staticfiles.views import serve
def custom_serve(request, path, insecure=False, **kwargs):
"""
Customize the response of serving static files.
Note:
This should only ever be used in development, and never in production.
"""
response = serve(request, path, insecure=True)
response['Access-Control-Allow-Origin'] = '*'
# if path.endswith('sw.js'):
# response['Service-Worker-Allowed'] = '/'
return response
urls 部分與問題相同:
from django.conf import settings
if settings.DEBUG:
# Allow custom static file serving (use with manage.py --nostatic)
from django.conf.urls.static import static
from CHANGE.THIS.PATH.views import custom_serve
urlpatterns += static(
settings.STATIC_URL, document_root=settings.STATIC_ROOT, view=custom_serve
)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.