[Django] routing system

Please read this article before browsing

Django project creation https://blog.csdn.net/Hudas/article/details/128764981?spm=1001.2014.3001.5501

URL is the abbreviation of Uniform Resource Locator. The Chinese name is Uniform Resource Locator. It is a concise representation of the location and access method of resources that can be obtained from the Internet. It is the address of standard resources on the Internet.

Every file on the Internet has a unique URL, which contains information indicating where the file is located and what the browser should do with it

A URL usually consists of the following parts:

scheme://host:port/path/?query-string=xxx#anchor

scheme: represents the access protocol, generally http or https and ftp, etc.

host: host name/domain name/ip address where resources are stored, such as www.baidu.com

port: port number, when you visit a website, the browser uses port 80 by default

path: the path to access resources, such as www.baidu.com/article/12, the following article/12 is the path

query-string: query string, such as www.baidu.com/s?wd=copy, followed by wd=copy is the query string

anchor: Anchor point, the front end is used for page positioning

All characters in the URL are in the ASCII character set. If there are non-ASCII characters, such as Chinese, the browser will encode them and then transmit them.

The URL is the entrance of the Web service. Any request sent by the user through the browser must be sent to a specified URL address, and then the server will return the response to the browser. Routing is a dispatcher used to handle the relationship between URLs and functions

When a user requests a page on the Django site, the routing system matches the path part of the url, and once the match is successful, it imports and executes the corresponding view to return the response

Django’s routing process is as follows:

① Find the global urlpatterns variable, that is, the urlpatterns variable defined in the study_django/urls.py file

② Match each element in the urlpatterns list to the URL one by one in order

③ Stop searching when the first match is found, and execute the corresponding processing function according to the matching result

④ If no match is found or an exception occurs, Django performs error handling

Tips: In the urls.py file under the project file directory, a variable urlpatterns is defined in the file, which is a list, each element of which is a url pattern, which defines urls and views Function Correspondence

1. Routing module

Routing modules in Django are generally named urls.py

Each routing module will contain a urlpatterns variable, which is a list of django.urls.path() or django.urls.re_path() instances

Main routing module

The outermost routing module, the entry point for routing analysis. Usually the urls.py module in the project directory

Subrouting Module

The other routes included in the main route are sub-routes, which are generally urls.py modules in their respective application directories, and you need to create urls.py yourself

2. Routing form

Django supports the following forms of routing

①Exact string format

An exact URL matches an action function, suitable for responding to static URLs, the URL string does not start with ‘/’, but must end with ‘/’, for example

path(‘admin/’, admin.site.urls),

path(‘articles/’, views.article_list),

path() function syntax format

path(route, view, kwargs=None, name=None)

Parameter Description

route: Matching request? path, can be understood as a criterion for matching URL (string type), when Django responds to a request, it Starting from the first item of urlpatterns, it will match the items in the list in order until a matching item is found, and then execute the view function mapped to the item or the lower-level route distributed by the include function

view: Refers to the view function that needs to be called after the route is successfully matched. (When Django finds a matching URL criterion, it will call this specific view function)

kwargs: You can pass extra parameters to the corresponding view function, which are optional parameters (dictionary type)

name: an alias for URL, which allows us to uniquely refer to it anywhere in Django, which is an optional parameter

Example 1
Create views.py in the study_django directory and write the following code

from django.http import HttpResponse

def article_list(request):
    return HttpResponse("article_list function")

Create a route in the study_django/urls.py file, the code is as follows

from django.contrib import admin
from django.urls import path
# Import custom views module
from . import views

urlpatterns = [
    path('admin/', admin.site.urls),
    # add add
    path('articles/', views.article_list),
]

Start the service, enter the URL http://127.0.0.1:8000/articles/ in the browser, the result is as follows

②Path converter format

Usually, while matching the URL, parameters are obtained and passed through the URL. The use of the path converter is very simple, just follow the ‘‘ syntax format in the capture symbol <>

path(‘articles//’, views.year_archive),

path(‘articles///’, views.month_archive),

path(‘articles////’, views.article_detail),

Format conversion Type Description
str matches non-empty characters except path separators ( / ), the default conversion type
int match 0 and positive integers
slug Match a string composed of letters, numbers, dashes, and underscores, a subset of str
uuid match a formatted UUID, such as 075194d3-6885-417e-a8a8-6c931e272f00
path matches any non-null character string, including path separators

Example 2

Create views.py in the study_django directory and write the following code

from django.http import HttpResponse

def year_archive(request, year):
    return HttpResponse(f'year_archive function accepts parameter year:{year}')

def month_archive(request, year, month):
    return HttpResponse(f'month_archive function accepts parameters year:{year},month:{month}')

def article_detail(request, year, month, slug):
    return HttpResponse(f'article_detail function accepts parameters year:{year},month:{month},slug:{slug}')

Create a route in the study_django/urls.py file, the code is as follows

from django.contrib import admin
from django.urls import path
# Import custom views module
from . import views

urlpatterns = [
    path('admin/', admin.site.urls),
    # add add
    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),
]

Start the service, enter the URL http://127.0.0.1:8000/articles/2023/ in the browser, the result is as follows

Start the service, enter the URL http://127.0.0.1:8000/articles/2023/03/ in the browser, the result is as follows

Start the service, enter the URL http://127.0.0.1:8000/articles/2023/03/python/ in the browser, the result is as follows

③Regular expression format

Regular expressions can also be used if the path and transformer syntax does not define URL patterns well

When defining routes using regular expressions, you need to use re_path() instead of path()

re_path() function syntax format

re_path(route, view, kwargs=None, name=None)

Note that unlike path(), the route part contains regular expressions; the view, kwargs and name parameters are the same as path()

In Python regular expressions, the syntax for naming regular expression groups is as follows

(?Ppattern)

Tips: The letter P in ‘?P’ used in regular matching needs to be capitalized; name is the group name, and pattern is the pattern to be matched

Example 3

Create views.py in the study_django directory and write the following code

from django.http import HttpResponse

def article_list(request):
    return HttpResponse("article_list function")

def year_archive(request, year):
    return HttpResponse(f'year_archive function accepts parameter year:{year}')

def month_archive(request, year, month):
    return HttpResponse(f'month_archive function accepts parameters year:{year},month:{month}')

def article_detail(request, year, month, slug):
    return HttpResponse(f'article_detail function accepts parameters year:{year},month:{month},slug:{slug}')

Create a route in the study_django/urls.py file, the code is as follows

# import path and re_path
from django.urls import path,re_path
# Import custom views module
from . import views

urlpatterns = [
    path('articles/list/', views.article_list),
    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),
]

Start the service, enter the URL http://127.0.0.1:8000/articles/list/ in the browser, the result is as follows

Start the service, enter the URL http://127.0.0.1:8000/articles/2017/ in the browser, the result is as follows

Start the service, enter the URL http://127.0.0.1:8000/articles/2017/08/ in the browser, the result is as follows

Start the service, enter the URL http://127.0.0.1:8000/articles/2017/08/DMU/ in the browser, the result is as follows

3. Routing distribution (use of sub-routing)

During the development process, as the complexity of the project increases, more and more routes are defined. If all routes are defined in the urlpatterns variable of the main route study_django/urls.py file, the code will be particularly messy

To do this, we can set the routes with the same prefix content as a group, and then use the include() function to include the grouped routes

Example 4

Add sub-routes in the main routing module study_django/urls.py as follows

from django.contrib import admin
from django.urls import path, include

urlpatterns = [
    path('admin/', admin.site.urls),
    # add add
    path('article/', include('article.urls')),
]

We take the routes with the prefix “article/” in the study_django/urls.py file as a group, and use the include() function to import the article.urls module, so we need to create a sub-routing module urls.py in the article directory, and write the following code

# import path
from django.urls import path
# Import custom views module
from . import views

# Map 'index/' and view views.index
urlpatterns = [
    path('index/', views.index)
]

Open article/views.py and write the following code

from django.http import HttpResponse

def index(request):
    return HttpResponse("Hello World, My name is article.")

After completing the above operations, re-run the service

We can access the following results through http://127.0.0.1:8000/article/index/ in the browser

Tips: The parameter name set in the path() function needs to be the same as the parameter name called in the view function!

4. Extended practice cases

Exercise Case 1

Knowledge points involved: the use of kwargs parameters in path()

Create views.py in the study_django directory and write the following code

from django.http import HttpResponse

def content(request, **kwargs):
    print(kwargs) # {'author': 'Andy', 'age': 18}
    print(kwargs. get("author")) # Andy
    author = kwargs. get("author")
    age = kwargs. get("age")
    return HttpResponse("{} is the author of this article, age is {}".format(author, age))

Create a route in the study_django/urls.py file, the code is as follows

# import path
from django.urls import path
# Import custom views module
from . import views

urlpatterns = [
    # Pass a Python dictionary as an additional parameter to the corresponding view function
    path('articles/', views. content, {"author":"Andy","age":18}),
]

Start the service, enter the URL http://127.0.0.1:8000/articles/ in the browser, the result is as follows

Exercise Case 2

Knowledge points involved: the use of the name parameter in path()

Create a route in the project directory study_django/urls.py file, the code is as follows

# include for distribution
from django.urls import path,include

# Main route: only used for distribution
urlpatterns = [
    path('article/', include("article.urls")),
]

Create a sub-routing module urls.py in the article directory and write the following code

from django.urls import path
from . import views

# Subroutes
urlpatterns = [
    path("test01/", views.test),
    # Here the parameter name is used for this path!
    path("content/",views.content,{"author":"Andy","age":18},name = "fox"),
]

Open article/views.py and write the following code

# redirect is redirection, reverse is a function that parses the name of url into url
from django.shortcuts import redirect,reverse
from django.http import HttpResponse
import time

# article applies the following view functions
def content(request, **kwargs):
    author = kwargs. get("author")
    age = kwargs. get("age")
    return HttpResponse("{} is the author of this article, age is {}".format(author,age))

#login page
def test(request):
    print("login successful")
    time. sleep(3)
    # The following two functions are exactly the same
    # return redirect("/article/content") # Jump to the singing page
    return redirect(reverse("fox")) # reverse can resolve the current fox to its corresponding url address, ie /article/content

Start the service, enter the URL http://127.0.0.1:8000/article/test01/ in the browser, wait for 3 seconds and then jump to http://127.0.0.1: 8000/article/content/, showing that Andy is the author of this article, and his age is 18

The above solves that no matter how the address of the url changes, as long as its name attribute remains unchanged, these redirections about it can be executed normally

The knowledge points of the article match the official knowledge files, and you can further learn relevant knowledgePython entry skill treeWeb application development Django258394 people are studying systematically