django dev服务器,添加头到静态文件 [英] django dev server, adding headers to static files

查看:171
本文介绍了django dev服务器,添加头到静态文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用django dev服务器(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 如下所示:



django.views.static导入的$ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $
覆盖`django.views.static.serve`,这将允许我们添加
自己的开发头。

喜欢`django.views.static .serve`,这只应该在
开发中使用,从不在生产中。

response = static_serve(request,path,document_root = document_root,
show_indexes = show_indexes)

response ['Access-Control-Allow-Origin' ] ='*'
返回响应

但是,只要有 INSTALLED_APPS 中的django.contrib.staticfiles 自动添加静态网址,似乎没有办法覆盖它们。删除 django.contrib.staticfiles INSTALLED_APPS 使这项工作,但是,如果我这样做,staticfiles模板标签不再可用。



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

解决方案

staticfiles app 覆盖核心 runserver 命令,但允许您禁用th e自动提供静态文件:

  python manage.py runserver --nostatic 


Using the django dev server (1.7.4), I want to add some headers to all the static files it serves.

It looks like I can pass a custom view to django.conf.urls.static.static, like so:

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)

And common.views.static.serve looks like this:

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

However, simply having django.contrib.staticfiles in INSTALLED_APPS adds the static urls automatically, and there doesn't seem to be a way to override them. Removing django.contrib.staticfiles from INSTALLED_APPS makes this work, however, if I do that, the staticfiles templatetags are no longer available.

How can I override the headers that are served for static files using the django development server?

解决方案

staticfiles app overrides the core runserver command but allows you to disable the automatic serving of the static files:

python manage.py runserver --nostatic

这篇关于django dev服务器,添加头到静态文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆