routing

This is the 18th day of my participation in the August Genwen Challenge.More challenges in August

How does Django handle a request

When a user requests a page on a Django site, here’s the algorithm the Django system uses to decide which Python code to execute:

  1. Django decides to use the root URLconf module. Normally, this is the value for the ROOT_URLCONF setting, but if the incoming HttpRequest object has the URlconf attribute (set via middleware), its value will be used instead of the ROOT_URLCONF setting.

  2. Django loads the Python module and looks for the urlpatterns available. It is django.urls.path() and/or Django.urls.re_path ()

  3. Django iterates through each URL pattern sequentially, then stops when the requested URL matches the first pattern and matches path_info.

  4. Once there is a URL match, Djagno imports and calls the relevant view, which is a Python function (or class-based view). The view gets the following parameters:

    • An HttpRequest instance.

    • If the matched URL contains an unnamed group, the match from the regular expression is provided as a positional parameter.

    • The keyword argument consists of any named part of the path expression matched and is overridden by any argument specified in the optional kwargs argument of django.urls.path() or django.urls.re_path().

  5. If no URL is matched, or if an exception occurs during the match, Django calls an appropriate error-handling view. Participate in Error Handling below

from django.conf.urls import url
​
urlpatterns = {  This is path. You can also check the version information in settings.pyUrl (regular expressions,views, parameters, aliases),}Copy the code
  • Regular expression: A regular expression string
  • Views: A callable object, usually a view function
  • Arguments: Optional default arguments (in dictionary form) to be passed to view functions
  • Alias: An optional name parameter

2. Regular expressions

R '^articles/2003/' r: native string ^: What to start with $: What to end with d: numbers {}: several numeric ranges w: letters [0-9][A-z] : numbers from 0 to 9 and characters from A to Z. Match one or more flags beyond the newline character? Zero or one * Zero or moreCopy the code

Matters needing attention

  1. Elements in UrlPatterns match regular expressions one by one, in written order, from top to bottom, and do not continue once they have been matched.
  2. To capture a value from the URL, simply place a pair of parentheses around it (grouping matches).
  3. There is no need to add a leading backslash, because every URL has one. For example, it should be ^articles instead of ^/articles.
  4. The ‘r’ before each regular expression is optional but recommended.
urlpatterns = [
    url(r'^admin/', admin.site.urls),
    url(r'^blog/$', views.blog),
    # blogs/2012/12/
    url(r'^blogs/[0-9]{4}/\d{2}/$', views.blogs),  # if we do not write $, we will be intercepted by the blog/2002, because the search is from the top down
    url(r'^blogs/[0-9]{4}/$', views.blogs), # blogs/2012/
]
Copy the code
APPEND_SLASH=True # set this to False and Django will not add '/' by defaultCopy the code

3, grouping

The parameters captured at the URL address are passed to the view function as positional arguments

Location pass parameter :() url(r'^blogs/([0-9]{4})/(\d{2})/$', views.blogs),  
url(r'^blogs/([0-9]{4})/$', views.blogs), # blogs/2012/
​
    Accept arguments in views.py
def blogs(request,x,y) : # a parenthesis to indicate a parameter (positional pass parameter)
    print(x,type(x))
    print(y,type(y))
    return HttpResponse("blogs")
Copy the code

4. Name groups

Parameters captured at the URL address are passed to the view function as keyword arguments

Keyword pass parameter :(? P< name >) (? P< name >) url(r'^blogs/(? P
      
       [0-9]{4})/(? P
       
        \d{2})/$'
       
      , views.blogs), 
    
def blogs(request,year,month) : The name must correspond to the keyword
    print(year,type(year))
    print(month,type(month))
    return HttpResponse("blogs")
    
def blogs(request,*args,**kwargs) : # tuples, and dictionaries, that works too
    print(args)
    print(kwargs)
Copy the code

Grouping and named grouping cannot be mixed. The captured argument is always a string

Case 1:

1. Url (r'^publishers_edit/(\d+)', views.publishers_edit), # retrives one or more numbers of 2. Def publishers_edit(request,id_pk) def publishers_edit(request,id_pk): HTML <a class=" BTN btn-primary btn-sm" href="/publishers_edit/{{i.peck}}"> edit </a>Copy the code

5. Specify default values in view functions

# urls. Py
from django.conf.urls import url
​
from . import views
​
urlpatterns = [
    url(r'^blog/$', views.page),  Num =1 is used as the default if nothing is caught
    url(r'^blog/page(? P
      
       [0-9]+)/$'
      , views.page),
]
​
In # views.py, you can specify a default value for num
def page(request, num="1") :
    pass
Copy the code

In the example above, the two URL patterns point to the same views-views.page – but the first pattern does not capture anything from the URL.

If the first pattern matches, the Page () function uses its default argument num= “1”, and if the second pattern matches, page() uses the num value captured by the regular expression.

6. Pass extra arguments to the view function

url(r'^blogs/([0-9]{4})/$', views.blogs,{"k1":"v1"}), # blogs/2012/
​
def blogs(request,*args,**kwargs):
    print(args)  #('2012',)
    print(kwargs)   #{'k1': 'v1'}
    return HttpResponse("blogs")
Copy the code