[Django] Front-end and back-end data transmission, query string, path parameters, form data, non-form data, request headers

1. Query string

To pass the parameters to the server at the front end, you can use a query string, that is, add one after the resource path? Number, and then splicing query parameters, for example http://localhost/XXXX/?name=pan&age=18

We write a class that receives the query string in the view function of a sub-application, and both get() and post() methods are implemented, because no matter which request method is used, query parameters can be received

urls.py

from . import views

urlpatterns = [
    path('request_info/', views.RequestInfo.as_view()),
]

views.py

from django.views import View
from django import http

# 接收查询字符串: http://localhost/XXXX/?name=pan&age=18
# 提取查询字符串参数不区分请求方式,即使客户端进行POST方式的请求,依然可以通过request.GET获取请求中的查询字符串参数。
class RequestInfo(View):
    def get(self, request):
        # 使用get()方法获取数据,若不存在该参数名,则可以设置默认值
        # 需要注意的是,如果出现重复赋值,get()方法只会获取最后一个数值
        name = request.GET.get('name', '小明')
        age = request.GET.get('age', '0')
        # 也可以直接使用键取值
        # print(request.GET['age'])
        
        # 也可以接收全部重复数值,例如下面的链接,age重复了 多次
        # http://localhost:8000/request_info/?name=xiaohei&age=18&age=20&age=22
        args = request.GET.getlist('age')  # 接收全部age的数值,并且保存在一个列表
        print(args)
        return http.HttpResponse('姓名是%s,年龄是%s' % (name, age))

    def post(self, request):
        name = request.GET.get('name', '小明')
        age = request.GET.get('age', '0')
        return http.HttpResponse('姓名是%s,年龄是%s' % (name, age))

After we register the sub-route and the main route, we can get the passed parameters normally.

2. URL path parameters

2.1 path() simple extraction

In addition to use? For splicing strings, the path can also pass parameters, such as http://localhost:8000/request_goods/22/33/, the last 22 and 33 of the url are two parameters, we can specify several specific parameters, and we can specify the parameters name

urls.py

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

urlpatterns = [
   ...
    # <>内表示参数的名字,引用的时候也要用这参数名
    path('request_goods/<page>/<gid>/', views.RequestGoods.as_view()),
    # 也可以指定参数的类型,如int
	# path('request_goods/<int:page>/<int:gid>/', views.RequestGoods.as_view()),
	...
]

views.py

from django.views import View
from django import http

# 获取url携带的路径参数
# http://localhost:8000/request_goods/22/33/
class RequestGoods(View):
    # 传入的两个参数page和gid要在路由表声明
    def get(self, request, page, gid):
        return http.HttpResponse('当前第%s页,第号%s商品' % (page, gid))

When specifying parameters in the routing list, you can specify the parameter type. There are 5 types by default

The default route converter:

DEFAULT_CONVERTERS = {
    
    
    'int': IntConverter(), # 匹配正整数,包含0
    'path': PathConverter(), # 匹配任何非空字符串,包含了路径分隔符
    'slug': SlugConverter(), # 匹配字母、数字以及横杠、下划线组成的字符串
    'str': StringConverter(), # 匹配除了路径分隔符(/)之外的非空字符串,这是默认的形式
    'uuid': UUIDConverter(), # 匹配格式化的uuid,如 075194d3-6885-417e-a8a8-6c931e272f00
}

If you feel that the default routing conversion is not enough, you can customize it, but because it is more troublesome, let's use regular matching directly when routing.

2.2 re_path() regular extraction

We can extract the data to be passed from the path when routing, and use the re_path() function to match

urls.py

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

urlpatterns = [
  	...
    # <>内表示参数的名字,引用的时候也要用这参数名
    path('request_goods/<page>/<gid>/', views.RequestGoods.as_view()),
    
    # 使用正则匹配手机号,并且指定参数名
    re_path(r'^request_phone/(?P<phone_num>1[3-9]\d{9})/$', views.ResponsePhoneNumber.as_view()),
	...
]

Note: When writing regular, 1. Use ^, $ to specify the string before and after, 2. Use parentheses to group aliases

view.py

from django.views import View
from django import http

# http://localhost:8000/request_phone/13977778888/
class ResponsePhoneNumber(View):
	# 这里的phone_num参数由路由时指定
    def get(self, request, phone_num):
        return http.HttpResponse('提取到的手机号是:%s' % phone_num)

3. Receive request body data

3.1 Receive form data

urls.py

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

urlpatterns = [
    ...
    path('formdata/', views.FormdataView.as_view()),
	...
]

views.py

from django.views import View
from django import http

# 接收表单数据
class FormdataView(View):
    # 注意,表单数据只能通过post获取
    def post(self, request):
        username = request.POST.get('username')
        password = request.POST.get('password')
        return http.HttpResponse('用户名是:%s,密码是:%s' % (username, password))

note:

  • Receive form data, which can only be processed by the post() method
  • If csrf middleware is blocked, you can open the project's settings.py to find the MIDDLEWARE list, and comment out the csrf item
3.2 Receiving non-form data

If the data sent by the client is not form data, it will be kept in the original format, and the binary data of type bytes can be obtained through the request.body attribute

Let's take json data as an example here

urls.py

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

urlpatterns = [
 	...
    path('formbody/', views.Bodydata.as_view()),
]

views.py

from django.views import View
from django import http
import json

# 除了查询字符串和表单数据,其他的数据都会被保留原始数据
# 例如由前端发送过来的json数据
class Bodydata(View):
    def post(self, request):
        json_str = request.body
        json_dic = json.loads(json_str) # 把字符串转换成对象
        username = json_dic.get('username')
        password = json_dic.get('password')
        print(json_str)
        return http.HttpResponse('通过非表单提交的数据,用户名:%s,密码: %s' % (username, password))

4. Receive request header data

When the browser requests the server, it will entrain data in the request header. These data can be obtained through the request.META property. We can retrieve the corresponding value by key. For example, we can retrieve the more commonly used

Request header Description
CONTENT_LENGTH String length of request header
CONTENT_TYPE MIME file type of the request body
HTTP_ACCEPT Acceptable types in response
HTTP_HOST Host address
HTTP_REFERER Associated address
HTTP_USER_AGENT Browser proxy

The request header sent by the browser is also in key-value pair mode, but the key of the browser is somewhat different from the key of Django value

If you want to view more request header information, you can print out request.META to see

In addition to the more commonly used request header data above, we can also send custom key-value pairs, which can be received on the server side using the get() method. It should be noted that the key will change and change to "HTTP_ Capital key"

views.py

from django.shortcuts import render
from django.views import View
from django.http import HttpResponse
import json


class FormdataView(View):
    def post(self, request):
        print('=' * 30)
        print(request.POST.get('name'))
        print('=' * 30)
        return HttpResponse('提交表单')

    def get(self, request):
    	# 取值的键发生变化,原有的键名变成大写,再加上“HTTP_”前缀
        print(request.META.get('HTTP_NAME', '没有值'))  
        print(request.META.get('HTTP_PASSWORD', '没有值'))
        return HttpResponse('非表单数据')

Use postman to send header key-value pair data
Insert picture description here

Guess you like

Origin blog.csdn.net/qq_39147299/article/details/108264932
Recommended