Routing system
In short, the role of Django's routing system is to establish a mapping between the function that processes the data within the views and the URL of the request. After the request arrives, according to the relationship entry in urls.py, find the processing method corresponding to the request, and return to the client HTTP page data
The URL rule definitions in the Django project are placed in the urls.py directory of Project,
The default is as follows:
URLadminurlpatterns = [ url (R ' ^admin/', Admin.site.urls),]
The URL () function can pass 4 parameters, 2 of which are required: regex and view, and 2 optional parameters: Kwargs and name. Here are the specific explanations:
- Regex:
A regex is a generic abbreviation for a regular expression, which is a syntax that matches a string or URL address. Django takes the URL address of the user request and compares each entry in the Urlpatterns list from the beginning to the urls.py file, once the match is encountered, immediately executes the view function or level two route of the entry map, and subsequent entries will no longer match. Therefore, the order in which URL routing is written is critical!
It is important to note that the Regex does not match the GET or post parameters or the domain name, for example, Https://www.example.com/myapp/,regex only attempts to match myapp/. For Https://www.example.com/myapp/?page=3,regex, only try to match myapp/.
If you want to delve into regular expressions, you can read some related books or monographs, but in Django practice you don't need much advanced regular-expression knowledge.
Performance Note: Regular expressions are precompiled when the urlconf module loads, so its match search is very fast and you usually don't feel it.
View
When a regular expression matches an entry, the encapsulated HttpRequest object is automatically used as the first parameter, and the value of the regular expression "captured" is passed to the view specified by the entry as the second argument. If it is a simple capture, the captured value is passed as a positional parameter, and if it is a named capture, it is passed as a keyword argument.
Kwargs:
Any number of keyword parameters can be passed as a dictionary to the target view.
Name
Naming your URL allows you to explicitly refer to it anywhere in Django, especially within a template. The equivalent of taking a global variable name to the URL, you just need to modify the value of the global variable, and the place where it is referenced throughout Django will be changed as well. This is a very old, simple and useful design idea, and this idea is everywhere.
1. Most basic mapping
The user accesses the Http://127.0.0.1:8000/index and then the backend uses the index () function to handle
urls.py
from django.conf.urls import include, urlfrom django.contrib import adminfrom app01 import viewsurlpatterns = [ url(r‘^admin/‘, admin.site.urls), url(r‘^index/$‘, views.index), ]
1. Define the function to process the data from the views.py surface under the created app
2. Import views in urls.py
3. Write an L mapping relationship between URL and processing function in Urlpatterns
4, URL mapping is generally a regular expression, "^" The beginning of the string, "$" the end of the string
5, when written \^$ do not enter any URL will not be returned in the Yellow pages, but return to the corresponding page in the following function. Generally this one will be written at the end of the URL. Such as
2. Dynamic routes placed in order
You can use the regular to match URLs, and a set of URLs using a map to fix
urlpatterns = [ url(r‘^host/(\d+)$‘, views.host), url(r‘^host_list/(\d+)/(\d+)$‘, views.host_list), ]
\^host/(\d+) $
The corresponding URL is: "HTTP://127.0.0.1/HOST/2" (\d+) is to match any number, in the pagination of flexible use.
You need to specify a formal parameter in Views.host to accept the value of (\d+) \$
def user_list(request,id): return HttpResponse(id)
\^host_list/(\d+)/(\d+) $
The corresponding URL is: "HTTP://127.0.0.1/HOST/8/9", the matching number will be in the form of parameters in order to pass to the corresponding function in the view
In Views.host_list, you need to specify two formal parameters, note: The order of this parameter is strictly in the order of the URL
def user_list(request,hid,hid2): return HttpResponse(hid+hid2)
3. Routing of the reference situation
Use the grouping method of regular expressions to pass URLs to functions in the form of parameters, which can be sorted out in order
urlpatterns = [ url(r‘^user_list/(?P<v1>\d+)/(?P<v2>\d+)$‘,views.user_list), ](?P<v1>\d+)正则表达式的分组,相当于一个字典, key=v1, value=\d+。 {"v1":"\d+"}
This parameter is then passed to the corresponding function in the views, which may not be in the order
def user_list(request,v2,v1): return HttpResponse(v1+v2)参数v1 = (?P<v1>\d+)参数v2 = (?P<v2>\d+)
4. Distribute different URLs according to different apps
If there is a lot of apps under a project, then you have to write a huge number of URLs in urls.py. This looks very inflexible and disorganized.
We can classify different URL requests according to different apps.
First, write the URLs map entry in the urls.py. Note To import the Include method
from django.conf.urls import include, urlfrom django.contrib import adminurlpatterns = [ url(r‘^app01/‘, include(‘app01.urls‘)), url(r‘^app02/‘, include(‘app02.urls‘)),]
This relationship means that the request to the URL "app01/" is given to the URLs under APP01 for processing.
Next, create a urls.py file under APP01 to process the requested URL and make it map to the views
from django.conf.urls import include, urlfrom app01 import viewsurlpatterns = [ url(r‘index/$‘, views.index),]
Want to request for URL: "http://127.0.0.1/app01/index/"
5. Develop a dynamic routing system for Django through the reflection mechanism
Defining categorical regular Expressions in urls.py
From Django.conf.urlsImport patterns, include, urlFrom Django.contribImport AdminFrom Dynamicrouter.activatorImport Processurlpatterns = Patterns (‘‘,# Examples:# URL (R ' ^$ ', ' DynamicRouter.views.home ', name= ' home '),# URL (r ' ^blog/', include (' Blog.urls ')), url (R ' ^admin/', include (Admin.site.urls)), (' ^ (? P<app> (\w+))/(? P<function> (\w+))/(? P<page> (\d+))/(? P<id> (\d+))/$ ', process), (' ^ (? P<app> (\w+))/(? P<function> (\w+))/(? P<id> (\d+))/$ ', process), (' ^ (? P<app> (\w+))/(? P<function> (\w+))/$ ', process), (' ^ (? P<app> (\w+))/$ ', process,{' function ':' Index '}),
Create activater.py in the same directory
#!/usr/bin/env python#coding: Utf-8From Django.shortcutsImport Render_to_response,httpresponse,redirectDef Process(Request,**kwargs):"' receives all requests that match the URL, dynamically specifies the method in the view by reflection based on the parameters in the request URL" ' app = Kwargs.get (' App ',None) function = Kwargs.get (' function ',None)Try:appobj = __import__ ("%s.views"%app) viewobj = GetAttr (Appobj, "views") Funcobj = GetAttr (viewobj, function) #执行view. py function and get its return value result = Funcobj (Request,kwargs) except (Importerror,attributeerror), E: # When the import fails, the custom 404 error return HttpResponse ( ' 404 Not Found ') except exception,e: #代码执行异常时, automatically jumps to the specified page return redirect ( '/app01/index/') return result
6.FBV and CBV
The so-called FBV and CBV refer to the correspondence between URL and view
- FBV function Base view/url/--and functions
- CBV class Base view/url/-Class
All of these are fbv ways. CBV is described below:
url(r‘^cbv‘,views.CBVtest.as_view()),
Class Cbvtest(View):Def Dispatch(Self, request, *args, **kwargs): Print ("Similar adorner: before") result = Super (cbvtest, self). Dispatch (Request, *args, **kwargs) print ("Like adorners: After")return resultDef Get(Self, request):# define get method, GET request executes this method print (Request.method) return HttpResponse ( ' Cbvget ') def post< Span class= "Hljs-params" > (self, request) : # define post method, POST request to execute this method print ( Request.method) return HttpResponse ( ' cbvpost ')
Django (URL) routing system