2015年1月29日木曜日

How Django processes a request

When a user requests a page from your Django-powered site, this is the algorithm the system follows to determine
which Python code to execute:
1. Django determines the root URLconf module to use. Ordinarily, this is the value of the ROOT_URLCONF
setting, but if the incoming HttpRequest object has an attribute called urlconf (set by middleware request
processing), its value will be used in place of the ROOT_URLCONF setting.
2. Django loads that Python module and looks for the variable urlpatterns. This should be a Python list of
django.conf.urls.url() instances.
3. Django runs through each URL pattern, in order, and stops at the first one that matches the requested URL.
4. Once one of the regexes matches, Django imports and calls the given view, which is a simple Python function
(or a class based view). The view gets passed the following arguments:
• An instance of HttpRequest.
• If the matched regular expression returned no named groups, then the matches from the regular expression
are provided as positional arguments.
• The keyword arguments are made up of any named groups matched by the regular expression, overridden
by any arguments specified in the optional kwargs argument to django.conf.urls.url().
5. If no regex matches, or if an exception is raised during any point in this process, Django invokes an appropriate
error-handling view. See Error handling below.
Example
Here's a sample URLconf:
from django.conf.urls import url
from . import views
urlpatterns = [
url(r'^articles/2003/$', views.special_case_2003),
url(r'^articles/([0-9]{4})/$', views.year_archive),
url(r'^articles/([0-9]{4})/([0-9]{2})/$', views.month_archive),
url(r'^articles/([0-9]{4})/([0-9]{2})/([0-9]+)/$', views.article_detail),
]
Notes:
• To capture a value from the URL, just put parenthesis around it.
• There's no need to add a leading slash, because every URL has that. For example, it's ^articles, not
^/articles.
• The 'r' in front of each regular expression string is optional but recommended. It tells Python that a string is
"raw" – that nothing in the string should be escaped. See Dive Into Python's explanation.
Example requests:
• A request to /articles/2005/03/ would match the third entry in the list. Django would call the function
views.month_archive(request, '2005', '03').
• /articles/2005/3/ would not match any URL patterns, because the third entry in the list requires two
digits for the month.
• /articles/2003/ would match the first pattern in the list, not the second one, because the patterns are
tested in order, and the first one is the first test to pass. Feel free to exploit the ordering to insert special cases
like this.
• /articles/2003 would not match any of these patterns, because each pattern requires that the URL end
with a slash.
• /articles/2003/03/03/ would match the final pattern. Django would call the function
views.article_detail(request, '2003', '03', '03').

0 件のコメント:

コメントを投稿