Django-url Scheduler-Introductory article

Source: Internet
Author: User
Tags python list

Django adheres to the MVC model and features it as an MTV model. The core of the model is to point to the processed function through the URL that the user accesses, and the function returns the corresponding result after processing. Therefore, the URL determines the user access to the portal, and the form processing of the submission address also needs to specify the URL. URLs are the portals of all functions, so the writing of URLs becomes very important.

Django's URL authoring involves Python's re module, the regular expression, which needs to be mastered in advance.

This article will be in conjunction with the official 1.8.2 documentation, if there is an unclear place to refer to the official documents, I have here to provide a Chinese translation: poke here

Before I write the instructions, let me introduce how Django handles a request:

  1. A request was made by the user. Django encapsulates information such as a user's request message into a HttpRequest object, and then passes through various middleware processing to arrive at the URL module for processing function selection.

2.Django to decide which module to use as a match, this is usually determined by the value of root_urlconf in settings.py, for example:root_urlconf = 'test_web.urls ' 。 It means that the module file (which is also known as the root module of the URL, can be modified) will use the URLs of Test_web (the project with the same name app) under this app. But if the incoming HttpRequest object has a urlconf attribute (set by the middleware request processing), this value is used to replace the root_urlconf setting. (There may be version differences)

3.Django loads the Python module and looks for the available urlpatterns variables. It is a list of Python, the elements of which are instances of Django.conf.urls.url ().

4.Django matches each URL pattern in a regular fashion, and then stops at the first match to the requested URL (which is also ignored below).

5. Once one of the regular expression matches, Django will import and invoke the given view, which is a simple Python function (or a class-based view). The view will have the following parameters:

A) a HttpRequest instance (which is why the first parameter of the view function, if requested, encapsulates the information for all HTTP request messages)

b) If the regular matching URLs are grouped in parentheses but are not named for the group, then the mode of the positional parameter is used to pass parameters to the view function.

c) If the grouping is named, the method of using the keyword to pass the parameter. However, Django.conf.urls.url () can be overridden by an optional parameter Kwargs.

6. If there is no match to the regular expression, or if an exception is thrown in the procedure, Django will invoke an appropriate error-handling view.

7. The function is finished and returns the result after processing.

examples of official manuals:
 fromDjango.conf.urlsImportURL from.ImportViewsurlpatterns=[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),]

Analysis:

1. To capture a value from a URL, simply place a pair of parentheses around it. (that is, group matching in the regular)

2. You do not need to add a leading backslash because each URL has a. For example, it should be ^articles rather than ^/articles. (Django automatically adds/after the domain name, this default behavior can be rewritten)

3. The ' R ' in front of each regular expression is optional but is recommended to be added. It tells Python that the string is "raw"--any character in the string should not be escaped. See Dive into Python for explanations.

Some examples of requests:

The/articles/2005/03/request will match the third pattern in the list. Django will call the function views.month_archive (Request, ' 2005 ', ' 03 ').

/ARTICLES/2005/3/does not match any URL pattern, because the third pattern in the list requires that the month should be two digits.

/articles/2003/the first pattern in the matching list is not the second, because the pattern matches sequentially, and the first Test matches first. Be free to insert special cases like this to detect the order of the matches.

/ARTICLES/2003 does not match any one pattern, because each pattern requires the URL to end with a slash.

The/articles/2003/03/03/will match the last pattern. Django will call the function views.article_detail (Request, ' 2003 ', ' 03 ', ' 03 ').

Named groups

  In the above example, although the parameters are passed, there is no known keyword to pass the argument. To use the keyword pass-through, only the grouping is named. For example: (? p<name>\d+), this grouping means matching one or more arbitrary numbers and passing them to the view function in the same way as Name = match to the number, such as name = ' 123 '.

However, it is important to note that the URL captures so that the parameters are string types, although \d represents a matching number in the regular, but when the parameter is passed, the string is passed. For example, the regular capture is 123, but the pass parameter is ' 123 '.

Official Examples
 fromDjango.conf.urlsImportURL from.ImportViewsurlpatterns=[url (r'^articles/2003/$', views.special_case_2003), url (r'^articles/(? P<YEAR>[0-9]{4})/$', views.year_archive), url (r'^articles/(? P<YEAR>[0-9]{4})/(? P<MONTH>[0-9]{2})/$', views.month_archive), url (r'^articles/(? P<YEAR>[0-9]{4})/(? P<MONTH>[0-9]{2})/(? P<DAY>[0-9]{2})/$', Views.article_detail),
]

Analysis:

The/articles/2005/03/request will call Views.month_archive (Request, Year= ' 2005 ', month= ' 03 ') function instead of views.month_archive (request, ' 2005 ', ' 03 ').

The/ARTICLES/2003/03/03/request will call the function views.article_detail (request, year= ' 2003 ', Month= ' ", day= ' 03 ').

matching/grouping algorithms

The following is the algorithm used by the URLCONF parser for named and unnamed groups in regular expressions:

1. If you have a named parameter, use these named arguments, ignoring the non-named parameters.

2. Otherwise, it will pass all the non-named parameters as positional parameters.

Depending on the additional options passed to the View function (below), the extra keyword arguments are passed to the view in either case.

Attention:

1. In a URL, the grouping cannot have the same name, or an error message. (Preliminary test)

2. The so-called named groupings use named arguments, ignoring unnamed parameters as follows:

URL (r'add/(\d+)/(? p<num1>\d+)/(? p<num2>\d+)/', add, name='add'),

def Add (Request, NUM1, num2):     = Int (num1)    = int (num2)    return httpresponse (NUM1 + num2)

Here, the request is HttpRequest, is the Django automatic transfer, we just look at the NUM1 and num2 two parameters can be. My handler function here requires 2 parameters in addition to the request, but I used three groupings in the URL, theoretically capturing 3 parameters.

However, when I visit http://127.0.0.1:8000/add/666/321/123/ , I get the result:

  

In addition, because the captured parameter is a string type, I use the Int () function for type conversion, if not:

def Add (Request, NUM1, num2):     return HttpResponse (NUM1 + num2)

The results are as follows:

Concatenation of strings, so that the captured parameters are all strings .

Okay, back to the chase. my function needs In addition to the request of 2 parameters, but I captured three in the URL, the result is the following two named group parameters, that is, the more out of the ignored .

  This is called when a named group is present, the non-named group is ignored.

  However, my URL is written like this:

URL (r'add/(\d+)/(? p<num2>\d+)/', add, name='add'),

  I want the previous unnamed group to pass to NUM1 by location and num2 to use the keyword parameter.

Now, I visit: http://127.0.0.1:8000/add/321/123/

The error message is that the function requires 3 parameters, and we give 2, which removes the automatically passed request, that is, we only capture 1 parameters.

At this point, look at this sentence: when a named group exists, the unnamed group is ignored .

Because the parameters captured by the non-named group are ignored, it causes us to pass one less argument.

At this time, you should know what it means to ignore here.

URLconf on what to look for

The requested URL is considered to be a normal Python string, urlconf on which to find and match. parameters for how get or post requests are not included and the domain name will be matched.

For example, in a http://www.example.com/myapp/request, URLconf will look for myapp/.

In the http://www.example.com/myapp/?page=3 request, URLconf will still find the myapp/.

URLconf does not check which method of request is used. In other words, all the request methods-that is, either the POST request, the GET request, or the head request method for the same URL-will match to the same function.

  However, we can restrict a function to be accessed only in some way, but this is not the URL here, and later.

the captured parameter is always a string

I've already demonstrated this in the example of Num1 and num2, and here's the thing to remember.

Specify default values for view parameters

This is not a Django-specific usage, it is the content of the function default parameter in Python. But Django can handle a few special situations here:

 from Import URL  from Import  = [    url (r'^blog/$', views.page),    URL (r  '^blog/page (? p<num>[0-9]+)/$', Views.page),
]

def page (request, num="1"    ): ... return .....

In the example above, two URL patterns point to the same view views.page--but the first pattern does not capture any values from the URL. If the first pattern matches, the page () function uses the default value "1" of the num parameter. If the second pattern matches, the page () will use the NUM value captured by the regular expression.

Performance

  Each regular expression in the Urlpatterns is compiled the first time they are accessed. This makes the system quite fast.

syntax of the urlpatterns variable

  Urlpatterns should be a python list that contains instances of URLs () in the list.

Error Handling

When Django cannot find a regular expression that matches the URL of the request, or when an exception is thrown, Django invokes an error-handling view.

The view used when these conditions occur is specified by 4 variables. Their default values should satisfy most items, but it is also possible to assign them further customizations.

See the custom error view for complete details.

These values can be set in your root urlconf. Setting these variables in other urlconf will not result in an effect.

Their values must be either callable or a string representing the full Python import path of the view, which can be easily invoked to handle error conditions.

These values are:

handler404--See django.conf.urls.handler404.

handler500--See django.conf.urls.handler500.

handler403--See django.conf.urls.handler403.

handler400--See django.conf.urls.handler400.

 

 In this Part I am also in the study, later study the results to share.

Django-url Scheduler-Introductory article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.