菜单

URL Dispatcher examples of Python exploration

2017年11月23日 - PHPer

URL

Dispatcher simple point to understand is that according to URL, the request to the corresponding method to deal with, it is a mapping of URL and View, its realization is also very simple, is a process of regular matching, predefined regular expressions and the regular expression corresponding to the view method, if the request URL in line with the regular expression, then distribute the request to the view method.

With this base, we start with a few questions and think ahead of time:

Where is the definition of this mapping? When there is a lot of mapping, what if effective organization?

How to get the parameters in URL and how to pass it to view method?

How to reverse URL in view or template?

Well, first look at a simple example:

From django.conf.urls import patterns, URL, include

Urlpatterns = patterns (‘,

URL (r’^articles/2003/$’,’news.views.special_case_2003′),

URL (r’^articles/ (\d{4}) /$’,’news.views.year_archive’),

)

Urlpatterns = patterns (”,

URL (r’^articles/ (? P< year> \d{4}) / (? P< month> \d{2}) /$’,’news.views.month_archive’),

URL (r’model/’, include (‘model_test.urls’)),

)

This code is a URL

The example of Dispatcher, which is defined in a separate Python module, in Django, is called URLconf, which is actually a configuration file implemented in Python code. In this configuration, the mapping between the URL path and the corresponding processing method is defined. In the Django, is to manage the relationship between the URLconf through the “tree” structure, the main configuration file in Django, called a ROOT_URL_CONF configuration, is used to specify the root URLconf, starting from the root of URLconf, matching one by one, until a match is found, this is what we mentioned above the answer to the first question, the following will be carefully analyzed.

In the example above, we can see 3 methods: patterns, URL, include. The URL method constructs a mapping relation object from URL to View, and patterns makes these mapping objects into a list of Python. What does include do? It’s what we’re talking about as a link to the tree structure, and include connects other URLconf to this URLconf, that is to say, include is a child node. The whole URL

Dispatcher system is constructed by these three methods, we focus on the introduction of these three methods, understand the three methods, the entire URL mapping mechanism will be very clear.

Def patterns (prefix, *args):

Pass

Def URL (regex, view, kwargs=None, name=None, prefix=”):

Pass

Def include (Arg, namespace=None, app_name=None):

Pass

(URL)

First look at the most important URL () method. The first parameter is regex regular expressions on behalf of URL, the second parameter specifies the regular expression and the mapping of the View, in addition, can also use the kwargs parameter, specify the default kwargs parameter to the view method, and name parameters, named for the URL, mainly used in the URL solution, the prefix is not very useful, not explain.

(URL) the final method constructs an object, we call it the URL mapping object, when the first visit to this object, URL, it will put the regular expression object in a compiler, and then stored in the object, so, again later, soon, the compiler will not repeat regular expressions. Here, the regular matching is actually using the python module of RE, and the process is roughly as follows:

Compile # first visit, and then stored in a URL object

Regex = re.compile (regex_str, re.UNICODE)

# every time when URL accesses are regular matching

Match = regex.search (path)

Kwargs = match.groupdict ()

Args = match.groups ()

Notice that the second questions mentioned above are related to how the parameters in the URL are acquired and how they are passed to the view method. Getting the parameters from URL is actually through the named in the re module

The concepts of groups and non-named groups are obtained by match.groupdict (), and named is obtained

Groups is actually a dictionary, the dictionary key is specified in URL, the dictionary will be passed as a kwargs parameter to view, and through the match.groups () is non-named

Groups is a tuple, that is, tuple, which is passed to view as a args parameter. However, args and kwargs can not exist at the same time, when kwargs is not empty, args will be empty, when kwargs is empty, args will be used, and the kwargs passed to view is only the default kwargs specified in the URL () method. That is, if you use named in URL

Groups, then non-named groups will be ignored if only non-named is used

Groups, it will be passed as a args parameter to the view method.

Okay, tangle up a lot, or analyze the examples we mentioned above, if we have URL and view:

Urls:

URL (r’^articles/ (\d{4}) /$’,’news.views.year_archive’)

URL (r’^articles/ (? P< year> \d{4}) / (? P< month> \d{2}) /$’,’news.views.month_archive’)

Views:

Def year_archive (request, *args, **kwargs):

Pass

Def month_archive (request, *args, **kwargs):

Pass

When we access the path of “articles/2014/”, the parsing process is as follows:

> > > import re

> > > regex = re.compile (r’^articles/ (\d{4}) /$’, re.UNICODE)

> > > match = regex.search (“articles/2014/”)

> > > match.groupdict ()

{}

> > > match.groups ()

(‘2014’,)

So the last parameter passed to the year_archive () method should be like this:

(Pdb) PP args

(u’2014′,)

(Pdb) PP kwargs

{}

When we access the path of “articles/2014/11”, the parsing process is as follows:

> > > import re

> > > regex = re.compile (r’^articles/ (? P< year> \d{4}) / (? P< month> \d{2}) /$’, re.UNICODE)

> > > match = regex.search (“articles/2014/11/”)

> > > match.groupdict ()

{‘year’:’2014′,’month’:’11’}

> > > match.groups ()

(‘2014′,’11’)

So the last parameter passed to the month_archive () method should be like this:

(Pdb) PP args

()

(Pdb) PP kwargs

{‘month’: u’11’,’year’: u’2014′}

Wordy sentence, because (URL) can specify a kwargs parameter, which is the URL associated view (kwargs) default parameter method, that is to say if URL (kwargs) in the specified method, it will be the content of this parameter, is passed to the kwargs parameter in the view method.

Well, at this point, the URL () method is basically clear, and the second problem is solved, as far as the name parameter is concerned, the details of the URL inverse solution are explained in detail.

Patterns ()

Next, let’s look at the patterns () method, which is actually quite simple, and it’s a list of URL mapping objects that are constructed by the URL () method. It is a required parameter is prefix, the prefix is that it contains the common prefix view, do so in order to avoid duplication of code, such as:

Urlpatterns = patterns (‘,

URL (r’^articles/ (\d{4}) /$’,’news.views.year_archive’),

URL (r’^articles/ (\d{4}) / (\d{2}) /$’,’news.views.month_archive’),

URL (r’^articles/ (\d{4}) / (\d{2}) / (\d+) /$’,’news.views.article_detail’),

)

It can be written:

Urlpatterns = patterns (‘news.views’,

URL (r’^articles/ (\d{4}) /$’,’year_archive’),

URL (r’^articles/ (\d{4}) / (\d{2}) /$’,’month_archive’),

URL (r’^articles/ (\d{4}) / (\d{2}) / (\d+) /$’,’article_detail’),

)

Note that by patterns () generated list is assigned to the urlpatterns variable, this variable is not defined, must be a good agreement, the default Django will go to URLconf to find this variable, maybe you can set a parameter in a certain place, to change the agreement, change this variable name.

In the 2 version of Django, this method will be discarded, but directly assigned to a list of urlpatterns, not too much discussion.

Include ()

We say include (), this is actually a difficult point, the key lies in the URL inverse solution there, Django document also did not say clearly, and the relationship is also messy, so, must be practical test, will understand.

As mentioned above, include () is the “tree” structure of the relationship, include will associate with other URLconf to the URLconf, rely on include (), can make Django URL design becomes very flexible and concise. (include) has three parameters, the first parameter needless to say, it specifies the path to include other URLconf, the key is the remaining two arguments, one is namespace,

One is app_name. What’s the use of it? In fact, these two parameters, together with the name parameter in the URL () method, together constitute the namespace of Django in URL, and the namespace is mainly for the URL inverse solution. What is the URL inverse solution? We can now find the corresponding view processing method according to a URL path of the request, and then, in turn, we can parse the corresponding URL in the view method, or template, according to the passed parameters, which is the URL inverse solution. Why do we need URL inverse solution? Is the program to write in order not to die, if we write in HTML in the path to death, then change it will be very troublesome, so often put these things into a variable variable, quoted in the program is the variable name, this is a common sense to write procedures. So, we can go from here to the bottom, from top to bottom.

In template, the inverse solution uses the {%url%} tag, and in view, the inverse solution is used in the `django.core.urlresolvers.reverse () method.

Well, first look at a simple example:

Mydjango/urls.py:

Urlpatterns = patterns (‘,

URL (r’model/’, include (‘model_test.urls’)),

)

Model_test/urls.py:

Urlpatterns = patterns (‘,

URL (r’^$’, views.index, name=’index’),

)

Mydjango/urls.py is root URLconf, which contains the model_test of URLconf, and there is a URL mapping object named index in urlpatterns in modul_test.

If we want to get the true path of the view corresponding to URL in template, then use template’s URL tag:

URL {%’index’%}

The result is: /model/.

Similarly, if you are in the view method, then use the reverve () method:

From django.core.urlresolvers import reverse

Reverse (“index”)

The same is true: /model/

In this case, we only use the name parameter in the URL () method, and we don’t use namespaces, because there’s no confusion in this simple situation, there’s no need to use namespaces, and there are two main ways to use namespaces:

When there are multiple applications in a project, the name of the URL mapping object defined in the application may be repeated, so that when the inverse is solved, Django cannot determine which application is actually

When in a project, the same application is deployed with multiple instances

发表评论

电子邮件地址不会被公开。