django staticfiles是否跳过中间件? [英] Does django staticfiles skip the middleware?
问题描述
我正在运行一个django 1.4.1应用程序。
I'm running a django 1.4.1 app.
我没有意识到只包括 django.contrib.staticfiles
into
INSTALLED_APPS
在您的设置中足以获取静态文件,而 settings.DEBUG
为True,也就是说,您不需要手动向url文件中添加任何内容。
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.
我也注意到,这绕过了django中间件。有没有人知道如何或为什么会发生这种情况?
I also noticed that this bypasses the django middleware. Does anyone know how or why this happens?
我刚刚创建了一个空白的新项目,我的views.py:
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)
我的urls.py:
from django.conf.urls import patterns, include, url
urlpatterns = patterns('',
url(r'^$', 'testapp.views.index', name='home'),
)
我的settings.py已经指定了一个目录来寻找静态文件,并且还添加了以下内容:
My settings.py has specified a directory to look for static files, and it also has this added:
MIDDLEWARE_CLASSES = (
'testapp.middleware.TestMiddleware',
...
)
使用这个中间件:
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?
推荐答案
我刚刚发布后发现...
I just figured this out after posting…
如果您使用 django-admin.py runserver
或 python manage.py runserver
,那么它会做一些额外的魔术添加一个常规中间件无法触摸的静态文件处理程序。
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.
您可以通过运行 django-admin.py runserver --nostatic
- 请参阅 django docs
You can disable this by running django-admin.py runserver --nostatic
— see the django docs
当你做 - nostatic
它会回落到您的应用程序中的URL,例如直接包含staticfiles_urls():
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()
那么您的中间件将运行这些URL(当然还有所有其他的)。
then your middleware will run for those urls (and of course all your others).
这篇关于django staticfiles是否跳过中间件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!