簡體   English   中英

django 開發服務器,向靜態文件添加標頭

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM