有趣的观察!以前从未注意到这一点。
当您访问 URL 时,Django 会尝试将其与所有定义的模式(按照定义的顺序)进行匹配。对于它匹配的第一个模式,将调用相应的视图。
但是如果没有定义 URL 模式,那么 django 将打印Not found: {url}
你在中看到的runserver
壳。正如预期的那样,它会尝试引发 404 异常。
但在debug
模式,它做了一些额外的事情。
让我们检查一下这个函数django/views/debug.py
:
def technical_404_response(request, exception):
# some extra code here
if (not tried # empty URLconf
or (request.path == '/'
and len(tried) == 1 # default URLconf
and len(tried[0]) == 1
and getattr(tried[0][0], 'app_name', '') == getattr(tried[0][0], 'namespace', '') == 'admin')):
return default_urlconf(request)
# more extra code here
Django 在这里尝试做的是检查它尝试了多少个 URL 模式。如果满足特定条件,则会尝试通过default_urlconf
。
这些具体条件是:
- 如果没有定义 URL 模式
- 如果尝试的 URL 是“/”,并且定义的唯一 URL 模式是针对
admin
app
所以我们从这里了解到,如果没有定义 URL 模式,那么 Django 将始终调用default_urlconf
。尝试删除admin
URL 也可以,然后访问任意随机 URL。你总会得到这样的东西:
Not Found: /random/url/
[11/Feb/2016 04:24:23] "GET /random/url/ HTTP/1.1" 200 1767
现在让我们看看default_urlconf
code:
def default_urlconf(request):
"Create an empty URLconf 404 error response."
t = DEBUG_ENGINE.from_string(DEFAULT_URLCONF_TEMPLATE)
c = Context({
"title": _("Welcome to Django"),
"heading": _("It worked!"),
"subheading": _("Congratulations on your first Django-powered page."),
"instructions": _("Of course, you haven't actually done any work yet. "
"Next, start your first app by running <code>python manage.py startapp [app_label]</code>."),
"explanation": _("You're seeing this message because you have <code>DEBUG = True</code> in your "
"Django settings file and you haven't configured any URLs. Get to work!"),
})
return HttpResponse(t.render(c), content_type='text/html')
(它返回一个正确的HttpResponse
=> 200 HTTP 代码)