【问题标题】:django dev server, adding headers to static filesdjango 开发服务器,将标头添加到静态文件
【发布时间】:2015-04-27 19:07:38
【问题描述】:

使用 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 就会自动添加静态网址,而且似乎没有办法覆盖它们。从INSTALLED_APPS 中删除django.contrib.staticfiles 可以使这项工作正常进行,但是,如果我这样做,则静态文件模板标签将不再可用。

如何使用 django 开发服务器覆盖为静态文件提供的标头?

【问题讨论】:

  • 嗯,我假设你有你的理由,但你不能通过将标题定义为通用模板上的块中的包含,然后在你的实际模板上扩展该模板来实现这一点。
  • 不是html文件,是字体文件。
  • 哦,好的。好吧,就像我说的,我认为你有你的理由,这就是为什么我没有把它写成答案。

标签: python django django-staticfiles


【解决方案1】:

staticfiles app overrides the core runserver 命令但允许您禁用静态文件的自动服务:

python manage.py runserver --nostatic

【讨论】:

    【解决方案2】:

    我发现作者的代码不适合我,我会收到如下错误:

    [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
        )
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-02-15
      • 2012-06-03
      • 2017-11-15
      • 2013-12-08
      • 2014-07-30
      • 2012-03-01
      • 1970-01-01
      • 2019-08-29
      相关资源
      最近更新 更多