django dev server, adding headers to static files

前端 未结 2 1015
[愿得一人]
[愿得一人] 2021-01-02 04:30

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.s

相关标签:
2条回答
  • 2021-01-02 05:08

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

    python manage.py runserver --nostatic
    
    0 讨论(0)
  • 2021-01-02 05:10

    I found the code of the author did not work for me, I would get errors like:

    [10/Dec/2020 18:08:13] "GET /static/img/foo.svg HTTP/1.1" 404 10482
    Not Found: /static/img/foo.svg
    

    I am using Django 3 if that makes a difference.

    This is what I did:

    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
    

    the urls part is the same as the question:

    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
        )
    
    0 讨论(0)
提交回复
热议问题