Does django staticfiles skip the middleware?

那年仲夏 提交于 2019-12-19 05:56:08

问题


I'm running a django 1.4.1 app.

I didn't realize that just including django.contrib.staticfiles into INSTALLED_APPS in your settings is enough to get static files served while settings.DEBUG is True, i.e., you don't have to manually add anything to your urls file.

I also noticed that this bypasses the django middleware. Does anyone know how or why this happens?


I just created a blank new project, my views.py:

from django.http import HttpResponse
def index(request):
    html = '<html><body>Logo: <img src="/static/logo.gif"></body></html>'
    return HttpResponse(html)

My urls.py:

from django.conf.urls import patterns, include, url
urlpatterns = patterns('',
    url(r'^$', 'testapp.views.index', name='home'),
)

My settings.py has specified a directory to look for static files, and it also has this added:

MIDDLEWARE_CLASSES = (
    'testapp.middleware.TestMiddleware',
    ...
)

Using this middleware:

from __future__ import print_function
class TestMiddleware(object):
    def process_request(self, request):
        print("[REQUEST]", request.path)

And when I make a request, this gets printed out:

[REQUEST] /
[18/Jan/2013 15:30:27] "GET / HTTP/1.1" 200 60
[18/Jan/2013 15:30:27] "GET /static/logo.gif HTTP/1.1" 200 2190
[REQUEST] /favicon.ico

Is it something to do with how the test server starts up?


回答1:


I just figured this out after posting…

If you're using django-admin.py runserver or python manage.py runserver, then it does some extra magic to add a staticfiles handler that your regular middleware can't touch.

You can disable this by running django-admin.py runserver --nostatic — see the django docs

And when you do --nostatic it will fall back to the urls in your app, such as if you include staticfiles_urls() directly with:

urlpatterns += staticfiles_urlpatterns()

then your middleware will run for those urls (and of course all your others).




回答2:


Found this issue when trying to modify request.path with middleware.

Discovered urls resolve against request.path_info not request.path



来源:https://stackoverflow.com/questions/14408017/does-django-staticfiles-skip-the-middleware

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!