Django2.0 Routing Layer-urlconf

Source: Internet
Author: User

DJango2.0 Routing Layer-urlconf
    • The URL configuration (URLconf) is like the directory tree of the Web site that Django supports.
    • Its essence is the mapping table between the URL and the view function to be called for the URL;
      • For a URL that is sent by the client, which logic code is called for execution.
      • In general, a path corresponds to a view function. It is not one by one correspondence!
      • Multiple paths can correspond to one view function, but one path cannot correspond to multiple view functions.
Urlpatterns

In urls.py, there is a default of Urlpatterns, which can be viewed as a list that holds the mapping relationship.
The path () method is commonly used in django2.0, and you can use the Re_path () method to be compatible with the URL () method in version 1.x.

    • The usage is basically the same, these methods mainly receive 4 parameters:
      • 2 are required: regext andview
      • 2 are optional: kwargs andname
    • Regex (Regular expression):
      • A regex is a generic abbreviation for regular expressions that can be used to match URL addresses.
      • The user requests the URL address, urls.py each entry in the Urlpatterns list from the beginning, and once a match is encountered, the view function or sub-route of the entry map is executed immediately, and subsequent entries will no longer match.
      • So, the order in which URL routing is written is very important!
      • The regex does not match the GET or post parameters or the domain name.
    • View (views function):
      • View refers to the function that handles the current URL request.
      • 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 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 (alias):
      • Naming your URL allows you to explicitly reference it anywhere in Django, especially within a template.
      • This is a very powerful feature, equivalent to a URL to take a global variable name, does not write URL matching address to die.
Instance
from django.contrib import adminfrom django.urls import pathfrom . import viewsurlpatterns = [    path(‘articles/2018/‘, views.special_case_2018),    path(‘articles/<int:year>/‘, views.year_archive),    path(‘articles/<int:year>/<int:month>/‘, views.month_archive),    path(‘articles/<int:year>/<int:month>/<slug:slug>/‘, views.article_detail),]

Note:

    • Captures the value in a URL, using angle brackets instead of parentheses;
    • You can convert a captured value to a specified type, such as an int in an example.
      • By default, the captured result is saved as a string type and does not contain/this special character;
    • The beginning of the matching pattern can not be added/, by default, each URL is preceded by a first/, common part, without special writing.

Matching examples:

    • /ARTICLES/2017/06/will match the third one and call views.month_archive (Request, year=2017, month=6);
    • /articles/2018/matches the first and calls views.special_case_2018 (request);
    • /ARTICLES/2018 does not match one, because it has a trailing slash, and all the patterns in the list end with a slash;
    • /articles/2016/05/building-a-django-site/will match the last one and call Views.article_detail (Request, year=2016, month=5, slug= " Building-a-django-site ".
Path Converter

By default, Django has the following path converters built into it:

    • STR: matches any non-empty string, but does not contain a slash/, default use;
    • int: matches 0 and positive integers, returns an int type;
    • Slug: Can be understood as annotations, suffixes, attachments, etc., is the URL in the last part of the explanatory character.
      • The converter matches any ASCII characters as well as connectors and underscores;
    • UUID: Matches an object in a UUID format. In order to prevent conflicts, it is mandatory to use dashes, all letters must be lowercase.
      • Example 0863561d3-9527-633c-b9b6-8a032e1565f0 . Returns a UUID object;
    • Path: Matches any non-empty string, with emphasis on the ability to include a path delimiter / .
      • This converter can help you match the entire URL rather than a paragraph of the URL string.
Customizing the Path Converter

Write a class and include the following members and attributes:

    • Class Property Regex: A regular Expression property in the form of a string;
    • To_python (self, Value) method:
      • Used to convert the matched string to the data type you want and pass it to the view function.
      • If the conversion fails, it must eject the valueerror exception;
    • To_url (self, Value) method:
      • A method that converts a Python data type to a URL, To_python the method's reverse operation.

For example, create a new converters.py file, the same directory as urlconf, and write the following class:

class FourDigitYearConverter:    regex = ‘[0-9]{4}‘def to_python(self, value):    return int(value)def to_url(self, value):    return ‘%04d‘ % value

After writing the class, register it in urlconf and use it, as shown below, to register a yyyy:

from django.urls import register_converter, pathfrom . import converters, viewsregister_converter(converters.FourDigitYearConverter, ‘yyyy‘)urlpatterns = [    path(‘articles/2018/‘, views.special_case_2018),    path(‘articles/<yyyy:year>/‘, views.year_archive),    ...]
Using regular expressions

Django2.0 's URL was changed to ' Config ', but it was still compatible with the old version.
The compatible approach, however, is to use the Re_path () method instead of the path () method.
Re_path () method in the bones, is basically the previous URL () method, but the location of the import has changed.

Here is an example, compare the grammar of the age of Django1.11, what is the difference?

from django.urls import path, re_pathfrom . import viewsurlpatterns = [    path(‘articles/2003/‘, views.special_case_2003),    re_path(r‘^articles/(?P<year>[0-9]{4})/$‘, views.year_archive),    re_path(r‘^articles/(?P<year>[0-9]{4})/(?P<month>[0-9]{2})/$‘, views.month_archive),    re_path(r‘^articles/(?P<year>[0-9]{4})/(?P<month>[0-9]{2})/(?P<slug>[\w-]+)/$‘, views.article_detail),]
    • The difference from the path () method is two points:
      • The year matches less than 10000 non-four digits, which is determined by the regular expression
      • All parameters passed to the view are string types.
        • Unlike the path () method, you can specify to convert to some type. Be careful when you receive parameters in the view.

Reference:
http://www.liujiangblog.com/blog/17/

Django2.0 Routing Layer-urlconf

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.