Django Framework 2: urls.py Routing Settings

Posted by shamilton on Sat, 07 Sep 2019 12:38:07 +0200

The routing system is to match the received requests according to the website address and specify the functions or classes to process the requests.


Routing system classification:

Web framework routing system is generally divided into two categories, FBV, CBV, Django both support, but some frameworks only support one.

FBV (Function Base View): Functions are view-based, and in views.py, functions are used to process requests.

CBV (Class Base View): Classes are view-based and use classes to process requests in views.py.



URLS.PY file routing configuration

Two functions, one is to go directly to the function, the other is to go to the lower urls.py routing

urlpatterns=[
    path(r'blog/', blog.views.index),
    path(r'bbs/', bbs.views.index)
]

Routing rule module matching function url,path,re_path:.

Django 1.XX uses url functions, rules, and fixed strings

After Django 2.XX, path and re_path are used.

from django.conf.urls import url        #django 1.XX uses url

from django.conf.urls import url, re_path        #django 2.XX uses url and re_path

from django.urls import path, re_path        #django 2.1X later integration, using path and re_path

The url: url() function passes four parameters, two required: regex and view, and two optional: kwargs, and name. That is, regular expressions and views are two required parameters.

Version 1.xx -- Complete regular and fixed matching

Version 2.xx - Keep


Path: Complete the matching of specified strings or formats. Function path() has four parameters, two necessary parameters: route and view, and two optional parameters: kwargs and name. That is, routing and view are required parameters

Version 2.1x later -- complete fixed matching

                

re_path: Regular matching, matching that path cannot complete

Version 2.xx -- Native location django.conf.urls

Back integration location django.urls


2. The path function:

Format: path (matching rules, views view functions or class methods,** kwargs, name)

Matching Rules: Rules are not supported, but they provide five matching patterns themselves

int matches 0 and positive integers, such as 1230
str matches any non-empty string but does not include /,
slug matches a string of letters, numbers, and crossbars and underscores.

uuid matches a uuid object, such as 075194d3-6885-417e-a8a8-6c931e272f00. (The object must contain dashes -- all letters must be lowercase)
The path matches all strings including /(meaning all the strings before and after the path)

                        

Views view or class method: views.py method of app, or class method

kwargs: parameters passed to views

Name: Back-end parsing, front-end finding parsing routing based on name value


3. path -- Matching rules:

Generally, there are three cases: strict matching, parameter matching and fixed format parameter matching.

from django.urls import path, re_path
import index.views
import pathtest.views

urlpatterns = [
    path(r'pathtest/', pathtest.views.index),
    #r'pathtest/'strictly matches, and the front-end using pathtest/1.2.3 parameters will report errors.
    # The current path, pathtest/ 1 2 3, didn't match any of these.

    path(r'pathtest <id_1> <id_2>', pathtest.views.index),
    #Using <> to capture values from the url, the pathtest / 1,pathtest.views.index functions must accept parameters, otherwise the error can be an argument or kwargs.
    # index() got an unexpected keyword argument 'id_1'

    path(r'pathtest <str:book_id>', pathtest.views.index),
    #Matching str-type parameters, named book_id, to views.index function
    #str, int, slug, uuid, path, five default matching patterns

]

4. path--views view or class method

Specify this rule to process views.py functions (FBV) or classes (CBV) of requests:

After processing the request, FBV: urls.py handles the request to the function index, after index processing, returns the pathtest.html page to the client.

            urls.py

from django.urls import path, re_path
import index.views
urlpatterns = [
    path(r'pathtest <str:book_id>', pathtest.views.index),
    #str, int, slug, uuid, path, five default matching patterns
]

            views.py

from django.shortcuts import render

def index(request,*args,**kwargs):
    para = []
    if kwargs:
        for k,v in kwargs.items():
            print(k,':',v)
    if args:
        for i in args:
            print(i)
    return render(request, 'pathtest.html', {'para': para})

        CBV:

Class needs to inherit the View class of django.views.generic

2. URLS.py routing forwarded to APP.views.class.as_view()

3. as_view() is an inheritance of the View class and does not need to be rewritten by itself.

4. Look at genericbase.py's as_view method and see how user requests are determined by hasattr

Execute the corresponding request method function through dispach

5. Customization can be achieved by registering new methods with http_method_names

Examples:

http://127.0.0.1:8000/pathtest1/ Display CBV1

http://127.0.0.1:8000/pathtest2/ Display CBV2

        URL.py

from django.urls import path, re_path
import pathtest.views
urlpatterns = [
    path(r'pathtest1/', pathtest.views.CBV1.as_view()),
    path(r'pathtest2/', pathtest.views.CBV2.as_view())
]

    APP:pathtest        Views.py

from django.view.generic import
class CBV1(View):
    def get(self,request,*args,**kwargs):
        return HttpResponse('<h1>CBV1</h1>')

class CBV2(View):
    def get(self,request,*args,**kwargs):
        return HttpResponse('<h1>CBV2</h1>')


5. kwargs: parameters passed to views

Dictionary parameters can be passed to views. Views functions can be received with arguments or parameters. When parameters are received with parameters, the parameters passed through path functions are always in front of the parameters passed by url addresses.

        urls.py

urlpatterns = [path(r'pathtest1/<int:url_args>', pathtest.views.CBV1.as_view(),{'since':'O-K'})]
#Pass {since':'O-K'} to views.py

        views.py

class CBV1(View):
    def get(self,request, *args, **kwargs):
    #Use arguments to receive def get(self,request, since, * args, ** kwargs):
        para = []
        if kwargs:
            for k,v in kwargs.items():
                print(k,':',v)
                para.append(v)
        return HttpResponse('<h1>CBV2{}</h1>'.format(para))
        
#Visit: http://127.0.0.1:8000/pathtest1/0010
#Web page display: CBV2['O-K', 10]

        

6. Name: After definition, use {% url'name value to refer to'%}, url refers to the current address.

When views render HTML template {% url'name value'%}, find the corresponding path route in urls.py according to the name value.

Replace the path matching rule string with the name value of the HTML template

        urls.py

urlpatterns = [
path(r'pathtest1/', pathtest.views.CBV1.as_view()),                #Define forward routing http://127.0.0.1:8000/pathtest1/access CBV1
path(r'pathtest2/<int:page_num>', pathtest.views.CBV2.as_view(), name='patht')        #Use name to define the reverse
# path(r'lllllllllll/<int:page_num>', pathtest.views.CBV2.as_view(), name='patht')        #Use name to define the reverse, and the change of matching rules does not affect name
]

        views.py

form django.shorsturc import HttpResponse, reverse
class CBV2(View):
    def get(self,request,page_num, *args, **kwargs):
        route_path=reverse('patht', args=(page_num,))
        #reverse, converted to the actual URL address, path is the name value in the urls, converted to a matching value
        #args: The number of parameters in the address, just write a few, such as four (page_num1,page_num2,page_num3,page_num4)
        print(route_path)                #Print it out
        return HttpResponse('<h1>CBV2:<br/>page_num:{}</h1>'.format(page_num))      #Depending on the link you click on, you get different return values.

class CBV1(View):
    def get(self,request, *args,**kwargs):
        return render(request, 'pathtest.html')

        html:

<body>
\ Use patht's name to define the URL routing, followed by 123 to get the value, so all three links will execute the CBV2 of views.
<a href="{% url 'patht' 100 %}">num</a>
<a href="{% url 'patht' 200 %}">numb/a>
<a href="{% url 'patht' 300 %}">numbe</a>
</body>

Results:

Access: http://127.0.0.1:8000/pathtest1/, click any link in html to execute CBV2 because the name value is defined.

Click on any link, route_path:/pathtest2/100 for views


7. Customize path matching rules. _

There are four matching rules in the path by default, int,str,slug,uuid,path,

You can also customize matching rules by defining classes, registering with register_converter, and using.

        urls.py

from django.urls import path, register_reverter
import pathtest.views

class NumLine:
#The first step is to define classes
    regex='[-0-9]+'
    def to_python(self, value):
        return str(value)                //Types can be converted and processed, and then returned
    def to_url(self, value):
        return str(value)                //Types can be converted and processed, and then returned

#The second step is to register a custom class in the converter and name it numline
register_reverter(NumLine,'numline')
       
urlpatterns=[
path(r'pathtest1/', pathtest.views.CBV1.as_view()),
path(r'ppppppppp/ <numline:data1> <numline:data2>',pathtest.views.CVB2.as_view(),name='patht')
#Matching parameters using self-defined numline
]

    APP:pathtest  views.py

from django.shortcuts import HttpResponse, render, reverse
from django.views.generic import View

class CBV1(View):
    def get(self,request):
        return render(request,'pathtest.html')

class CBV2(View):
    def get(self,request,data1, data2):
        full_path = reverse('patht',args=(data1,data2))
        return HttpResponse('<h1>Full path: {}<br />CBV2:<br/>page_num:{},{}</h1>'.format(full_path, data1, data2))

        pathtest.html

<a href="{% url 'patht' '-0--' 1111 %}">number</a>        //When character parameters are passed in, quotation marks must be added.
<a href="{% url 'patht' -2344 2222 %}">number</a>         //Here's - no error, because it's identified as a negative number
<a href="{% url 'patht'  3323 3333 %}">number</a>

Result: When accessing, only incoming - and 0-9 are recognized, and other parameters are reported as errors.


8. path routing is distributed to urls.py (secondary routing) of APP.    

Use the include method to specify, and include is imported from django.urls

Format: path(r'pathreg/',include('app.urls'), include('APP name. APP routing file')

            project:     urls.py

from django.urls import path, include

urlparrents=[
path(r'pathreg/',include('pathtest.urls')),
]

            app:         urls.py

from django.urls import path, include
from pathtest import views
urlparrents=[
path(r'',views.CBV1.as_view()),
path(r'index/',views.CBV2.as_view()),
]

            app:        views.py

from django.shortcuts import HttpResponse
from django.views.generic import View

class CBV2(View):
    def get(self,request):
        return HttpResponse('<h1>index page</h1>')

class CBV1(View):
    def get(self, request):
        return HttpResponse('<h1>default page<h1>')

Result: http://127.0.0.1:8000/pathreg/, matched pathreg by project urls routing file, distributed to app urls routing file, calling CBV1 to display default page

http://127.0.0.1:8000/pathreg/index, matching pathreg with the project ed urls routing file, matching index with the urls routing file distributed to app, calling CBV1 to display index page


9. re_path: Regular matching is supported, and other parameters are the same as path

The same url functionality as Django version 1.xx

path(r'', views.CBV1.as_view()),

re_path(r'index$', views.CBV2.as_view()),
# http://127.0.0.1:8000/pathtest/1111111111111index

re_path(r'^index', views.CBV2.as_view()),
# http://127.0.0.1:8000/pathtest/index1111111111111

re_path(r'index', views.CBV2.as_view()),
#This is the point. DBV2 will be found as long as there are continuous index es

re_path(r'^[a-zA-Z][_0-9a-zA-Z]{5,9}$', views.CBV2.as_view())
#Matching starts with letters, followed by numbers or underscores or letters. The shortest path is 6 and the longest path is 10 characters.
#Note: The {5,9} matches 6,10 characters because the first one is not included in the {5,9} option.
#http://127.0.0.1:8000/pathtest/i_d111ex11 matching


10. Adding a custom submission method to CBV:

Find the django.views.generic.View class,

By default, methods in the http_method_names list are provided.

The as_view function makes some judgments such as parameters.

Finally, the dispach method is returned.

dispach executes corresponding functions through getattr


Add a custom prompt method:

1) Add a method name to the http_method_names list, http_method_names.append('kill')

2) Define kill function in app.views.py


By rewriting dispach methods, add custom operations to all methods

    def dispatch(self, request, *args, **kwargs):
        print('Operation before operation')
        obj = super(Cbv,self).dispatch(request, *args, **kwargs)
        print('Operation code after operation')
        return obj




Topics: Python Django