Python automated operations: Django URL Routing

Source: Internet
Author: User

Get ready
Create a new Django project first

Django-admin Startproject Urltest

After entering the directory where manage.py is located

./manage.py Startapp app1./manage.py STARTPAP app2

At this point we have created a new project named Urltest, with two modules named App1 and APP2 respectively. (The tree directory structure is as follows)

.├── app1│   ├── __init__.py│    ├── admin.py│   ├── apps.py│   ├── migrations│   │    └── __init__.py│   ├── models.py│   ├──  tests.py│   ├── urls.py│   └── views.py├── app2│    ├── __init__.py│   ├── admin.py│   ├── apps.py│    ├── migrations│   │   └── __init__.py│   ├──  models.py│   ├── tests.py│   └── views.py├── db.sqlite3├──  manage.py└── urlTest    ├── __init__.py    ├──  settings.py    ├── urls.py    └── wsgi.py 


In the settings.py we can see:
root_urlconf = ' Urltest.urls '
# All URLs accessed by the browser will be configured in the urls.py in the Urltest directory,
urls.py added the URL of the admin module by default:

# urlTest.urls.py from django.conf.urls import URL, includefrom django.contrib import adminurlpatterns = [url (r ' ^admin /', admin.site.urls),]

That is, each URL is mapped to a specified view function, where the function defined in views accepts a request and returns a response.
If the working principle of the view is not clear, can refer to here request-response.

Write code here
Regular expressions and named groups

First in the App1 module through the regular expression of the corresponding dynamic matching of the year, month, month and day type of URL.
By default, there is no urls.py file in the App1 module, and after we have created it, we also need to add the following in Urltest urls.py:

URL (r ' ^app1/', include (' App1.urls ')) # This includes the urls.py file for the App1 module and then writes the dynamic regular expression in App1 under the new urls.py module: # app1.urls.pyfrom Django.conf.urls import Urlfrom. Import viewsurlpatterns = [url (r ' ^$ ', views.index), url (r ' ^ ([0-9]{4})/$ ', views.pattern1), url (r ' ^ ([0-9]{4})/(0?) [1-9]|1[0-2])/$ ', views.pattern2), url (r ' ^ ([0-9]{4})/(0?[ 1-9]|1[0-2])/(0?[ 1-9]| [1-2] [0-9]|3[0-1])/$ ', views.pattern3), #记得加上 ^ and $ Otherwise, month and day matches will be matched by the year]

I use the diagonal "/" as the symbol of the dividing date, but why is the diagonal bar preceded by parentheses? Because when you add parentheses, Django can capture this value from the URL and pass it to the corresponding views function, which of course uses positional arguments.
After matching the URL to the specified views function, I returned the HttpResponse:

# app1.viewsfrom django.shortcuts Import renderfrom django.http import httpresponse# Create your views here.def index (req uest): Return HttpResponse (' index ', ' Text/plain ') def pattern1 (Request, year): Return HttpResponse (year, ' Text/plain ') def pattern2 (request, year, month): Return HttpResponse (year + month, ' Text/plain ') def pattern3 (request, year, month, Date): Return HttpResponse (year + month + date, ' Text/plain ')

Just now when we were using parentheses to pass arguments, we were the positional arguments, so what if we wanted to use the keyword to pass the argument?
This is when we use named groups, and the regular expression syntax for named groups is (?). P<name>pattern), where name refers to the name of the passed parameter, pattern refers to the matching pattern.
Therefore, the following code is exactly equivalent to the preceding regular expression + parenthesis:

# app1.urls.pyfrom Django.conf.urls Import Urlfrom. Import viewsurlpatterns = [url (r ' ^$ ', views.index), url (r ' ^ (? P<YEAR>[0-9]{4})/$ ', views.pattern1), url (r ' ^ (? P<YEAR>[0-9]{4})/(? P<month>0? [1-9]|1[0-2])/$ ', views.pattern2), url (r ' ^ (? P<YEAR>[0-9]{4})/(? P<month>0? [1-9]|1[0-2])/(? P<date>0? [1-9]| [1-2] [0-9]|3[0-1])/$ ', views.pattern3),]

Finally, it is worth noting that the arguments in the views function are the default parameters that can be used, and that you can use regular expressions to set the parameters that are not captured (which can be used in nested parameters), such as syntax (?: ...).
In addition to capturing URL parameters, we can transfer additional data directly from the URL function to the view function.

# urls.py# replaces index's Urlurl (R ' ^$ ', Views.index, {' string ': ' Hello world! '}) # Views.pydef Index (Request, String): Return HttpResponse (String, ' Text/plain ')

If additional data is transferred inside the URL function that contains the Include function, the additional data is transferred to each line of the included urls.py URL function.
URL Patterns and namespaces

Each URL function on the URL patterns is a URL pattern that is represented in Django using Class Django.core.urlresolvers.RegexURLPattern.

While URL patterns represents a URL resolver (URL resolver), using the Include function to include other URL configuration modules is also interpreted as a URL resolver. Use class Django.core.urlresolvers.RegexURLResolver to represent it in Django.

Namespaces are divided into two main types, the instance namespace (instance namespace) and the application namespace (application namespace).

Why do we need namespaces?
Before, if we were to reverse-check the URL by using the Name property in the URL pattern, but the Name property was easy to duplicate and not reusable, we would not be able to tag it with a simple name attribute when we were deploying a URL configuration module multiple times.

How do I set the instance namespace and apply namespaces?

# include function Apiinclude (ARG, Namespace=none, App_name=none) # Namespace Set instance namespace, App_name Settings app namespace # can't just set app_name, or it will error , the following is an error source if App_name and not namespace:raise valueerror (' must specify a namespace if specifying App_name. ')

In general, different instances under the same application should have the same application namespace, but this does not mean that different apps can use the same instance namespace because the instance namespace is unique across all of your projects.
URL Reverse resolution


URL Reverse resolution is typically implemented through the reverse function and the URL tag in the template.
Let's start with a look at the URL reverse parsing mechanism in the Django Official document:

    reversing namespaced urls    when given a  namespaced URL  (e.g.  ' Polls:index ')  to resolve, Django splits  the fully qualified name into parts and then tries the  Following lookup:        first, django looks for  a matching application namespace  (in this example,  ' polls ') .  this will yield a list of instances of that application.         If there is a current application  defined, django finds and returns the url resolver for that  instance. the current application can be specified with the  current_app argument to The reverse ()  function.        the url template  tag uses the namespace of the currently resolved view as  the current application in a requestcontext. you can override  this default by setting the current application on the  request.current_app attribute.        if there is  no current application. django looks for a default application  instance. the default application instance is the instance that  has an instance namespace matching the application namespace  (in  this example, an instance of polls called  ' polls ') .         if there is no default application instance, Django will pick  the last deployed instance of the application, whatever its  instance name may be.        if the provided  namespace doesn ' t match an application namespace in step 1,  django will attempt a direct lookup of the namespace as  an instance namespace.

In addition to the last view name identified as the name tag, each previous name is first identified as the application namespace (the first), and is identified directly as an instance namespace if no matching application namespace is found (fifth).
When you identify the application namespace, and then see if the current application has no definition (ie, current_app, it is more likely to cause misunderstanding, the current application is not the application of namespaces, on the contrary, it refers to the instance namespace), if defined, Look for the value of Current_app (second) directly under the list of instance namespaces that have been identified by the application namespace.
If the value of Current_app is not found under the instance namespace list, it looks for the default instance namespace, the instance namespace with the same name as the application namespace. (article III)
If the default instance namespace is not found, Django returns the URL of the last deployed instance namespace. (Fourth article)

We still use concrete examples to illustrate the reverse parsing mechanism.
In the previous example, the App1 module and the APP2 module were defined, and then two of their instances were generated.

# urltest.urls.pyfrom django.conf.urls import url, includefrom django.contrib  import adminurlpatterns = [    url (R ' ^admin/',  admin.site.urls),     url (R ' ^app2/first/',  include (' App2.urls ',  namespace= ' first ',  app_name= ' App2 '),     url (R ' ^app2/second/',  include (' App2.urls ',  namespace= ' second ',  App_name= ' app2 '),     url (R ' ^app1/third/',  include (' App1.urls ',  namespace= "third ",  app_name= ' App1 '),     url (R ' ^app1/fourth/',  include (' App1.urls ',  Namespace= "Fourth",  app_name= ' App1 '),]# app1.views.pyfrom django.core.urlresolvers import  reversefrom django.http import httpresponseimport pdbdef index (request,  String):     pdb.set_trace ()     return httpresponse (string,  ' Text/plain ')

In the test environment of the PDB we use the reverse function to determine separately.

(PDB) reverse (' First:index ') u '/app2/first/' (PDB) reverse (' Second:index ') u '/app2/second/' (PDB) reverse (' third: Index ') u '/app1/third/' (Pdb) reverse (' Fourth:index ') u '/app1/fourth/'

As we can see, the instance namespace uniquely identifies the entire project URL.

(PDB) reverse (' App1:index ') u '/app1/fourth/' (PDB) reverse (' App2:index ') u '/app2/second/'

When we use the application namespace, the Django reverse parsing mechanism cannot find the default instance namespace without providing Current_app, and can only return the instance namespace of the last deployment.

(PDB) reverse (' App1:index ', current_app= ' third ') U '/app1/third/' (PDB) reverse (' App1:index ', current_app= ' fourth ') U ' /app1/fourth/' (PDB) reverse (' App2:index ', current_app= ' first ') U '/app2/first/' (PDB) reverse (' App2:index ', Current_ app= ' second ') U '/app2/second/'

After the instance namespace is provided, the URL can be uniquely determined even with the app namespace.
Finally we re-add the default instance namespace.

# urltest.urls.pyfrom django.conf.urls import url, includefrom django.contrib  import adminurlpatterns = [    url (R ' ^admin/',  admin.site.urls),     url (R ' ^app2/default/',  include (' App2.urls ',  namespace= ' app2 ',  app_name= ' App2 '),     url (R ' ^app2/first/',  include (' App2.urls ',  namespace= ' first ',  App_name= ' app2 '),     url (R ' ^app2/second/',  include (' App2.urls ',  namespace= ' Second ',  app_name= ' app2 '),     url (R ' ^app1/default/',  include (' App1.urls ',  Namespace= "App1",  app_name= ' App1 '),     url (R ' ^app1/third/',  include (' App1.urls ') ,  namespace= "Third",  app_name= ' App1 ')),     url (R ' ^app1/fourth/',  include (' App1.urls ',  namespace= "fourth",  app_name= ' App1 '),]# pdb (PDB)  reverse (' App1:index ') u '/app1 /default/' (Pdb) &nbsP;reverse (' App2:index ') u '/app2/default/' 

The last thing to remind is, do not assume that different applications can have the same instance, namespace must be unique!


This article is from the "Hyun-dimensional" blog, please be sure to keep this source http://xuanwei.blog.51cto.com/11489734/1980442

Python automated operations: Django URL Routing

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.