Django framework learning -- 2 -- routing configuration & request

Posted by mmj on Sun, 16 Jan 2022 22:34:50 +0100

The core content of this article:

1. Two different routing configuration methods

2. Related concepts of post and get requests and their interaction with browsers

1. General routing configuration method

        settings. "ROOT_URLCONF" in py specifies the location of the urlpatterns configuration list in the main routing file

For example, the following view functions will be found in the path('page/2022/', views.page_2022_view).

path() function
Import modefrom django.urls import path
grammarpath(route matches the request path, views specifies the view processing function corresponding to the path, name= None, address alias)

1.1 using the path converter to match URLs

converterFor example: path ('page / < int: Page > ', views. XXX)Syntax: < converter type: custom name >

For example, the results of

Converter type

strMatch non empty characters other than '/' (usually)
intMatch 0 or any positive integer and return an int (usually)
slug

Match any short label consisting of ASCII letters or numbers, hyphens and underscores. Detail / < slug: SL > -- > / detail / this is djang

pathMatch non empty fields, including path separator '/'

1.2 use the converter function to write a small computer

Matching format: http://127.0.0.1:8080/ Integer / operator / integer

# urls.py
import share.views as shview
path('int:n>/<str:op>/<int:n>',shview.cal_views)
# views.py
def cal_views(request, a, op, b):
    if op not in ['add','sub', 'mul','div']:
        return HttpResponse('your op is wrong')
    result = 0
    if op == 'add':
        result = a+b
    if op == 'sub':
        result = a-b
    if op == 'mul':
        result = a*b
    if op == 'div':
        result = a/b
    return HttpResponse('Operation result:%s'%(result))

Final result:

2. Use regular routing configuration method

2.1 further requirements: there are requirements for the number of digits of an integer, for example, it can only calculate the operation between two digits

re_path() function
Introduction modefrom django.urls import re_path
grammarre_path(reg, view, name=xxx)
characteristicMatch the extracted value for keyword parameter transfer, which is the same as the path() function

Solution: re_ path(r'^(?P<x>\d{1,2}/(?P<op>\w+)/(?P<y>\d{1,2})$‘, views.cal_view),

Named grouping pattern (? P < name > pattern)

r'str'Original string
^Start with the following character or group
?P<x>

Define a named group of x, w + multiple letters

2.2 example 2: matching date

Matching format: http://127.0.0.1:8080/birthday/(year)/(month)/(day)

#urls.py
import share.views as shview 
re_path(r'^birthday/(?P<y>\d{4}/(?P<m>\d{1,2})/(?P<d\{1,2}))$',shviews.birthday_view)
#views.py 
def birthday_view(request ,y ,m ,d):
    html = "{}year{}month{}day".format(y,m,d)
    return HttpResponse(html)

 3. Request and response

The request is the data sent by the browser to the server through HTTP protocol, and the response refers to the data that the server makes corresponding processing after receiving the request and then replies to the browser segment.

3.1 request method of HTTP protocol

There are the following: get, head, post, put, delete, connect, options (server performance),

TRACE (echo the request received by the server (diagnosis, test)).

After django receives the request from http protocol, it will create an HttpRequest object according to the request data; As shown in the following code, test_ The first parameter of the request view function is the request object by calling test_ The request function displays the corresponding function method functions.

from django.http import HttpResquest,HttpResponse 

def test_request(request):
    print('path info is', request.path_info) # Use get_full_path() displays the full path
    print(''method is', request.method) 
    print('querystring is', request.GET) # Display query string
    return HttpResponse('test request ok')
​

3.2 response

HTTP response status code:

  • 200 - Request successful
  • 301 - resources (web pages, etc.) are permanently transferred to other URL s
  • 302 - resources (web pages, etc.) are temporarily transferred to other URL s
  • 404 - the requested resource (web page, etc.) does not exist
  • 500 - internal server error

Response object HttpResponse(content=, content_type=, status =)

For example, return HttpResponseRedirect('/page/1') redirects resources to another url

3.3 get request and post request

The following functions separate post and get

def test_get_post(request):
    if request.method == 'GET':
        print(request.GET['a'])
        print(request.GET.get('c','no exist'))
        return HttpResponse(POST_FORM)
    elif request.method == 'POST':  # The server accepts the request
        print('uname is ',request.POST['uname'])
        return HttpResponse('post is ok')
    else:
        pass
    return HttpResponse('--test get post --')

The GET method in request is similar to that in POST

request.GET ['parameter name']It is obtained in the form of a dictionary, and no keyError will be triggered
request.GET.getlist() Multiple key s with the same name appear in the query string. Take out the value to form a list. Application scenario: questionnaire survey - interests - check box

The post method is applicable to the submission of private data. The client transmits the data to the server through post requests such as forms

<form method = 'post' action='/login'> 

    <input type ="text" name= "username">

    <input type= 'submit' value = 'Sign in'>

</form>
<!-- post form ->

When the above addition is completed in the routing and view module, enter the url: http://127.0.0.1:8080/test_get_post Errors will be found; Because post submission will have a network attack CSRF (let's have a general understanding)

Solution:

  • Note Django. In middleware (settings.py) middleware. csrf... That line won't report mistakes
  • In django, we need to add {%csrf_token%} to the form of templates

Final result:
 

 
 

Course address: 2021 latest Django full set of videos (quick start of Django framework)_ Python full stack_ Beep beep beep_ bilibili

Topics: Python Django Back-end