Django之2(request和response) ╰半橙微兮° 2022-05-20 07:00 131阅读 0赞 # jango中的请求与响应 # ## 一.请求request ## django中的request用来获取前端传过来的数据,那么前端数据的发送方式有多种,每一种传输方式在后端对应的接收方式也不同,所以我们首先来看前端的几种数据发送方式: ### 1.url路径参数 ### 对于这种数据,它在前端的url中,比如:www.baidu.com/id/ 我们就可以获取这个url中的id 方法: 在定义好的视图函数或者视图类的函数中的参数加上这个id即可 比如: 1. defweather(request, id): 2. print( 'id=%s' % id) 3. return HttpResponse( 'OK') ### 2.查询字符串 ### 什么是查询字符串?看下边的例子就好 www.baidu.com/data/?a=10&b=20&a=30 (这个路径中有两个a,因为前端有时会有一键多值的情况) 对于这种请求怎么获取a,b这两个数据呢 我们可以通过request.GET属性来获取(HttpRequest对象的属性GET、POST都是QueryDict类型的对象,通过QueryDict对象request.GET/request.POST来获取一键多值的数据) 重要:查询字符串不区分请求方式,即假使客户端进行POST方式的请求,依然可以通过request.GET获取请求中的查询字符串数据。 方法: 1. defqs(request): 2. a = request.GET.get( 'a') 3. b = request.GET.get( 'b') 4. alist = request.GET.getlist( 'a') 5. print(a) *\# 30* 6. print(b) *\# 20* 7. print(alist) *\# \['10', '30'\]* 8. return HttpResponse( 'OK') ## ## ### 3.请求体里边的数据 ### ### ### ### ### ### ### ##### 请求体数据格式不固定,可以是表单类型字符串,可以是JSON字符串,可以是XML字符串,应区别对待。 可以发送请求体数据的请求方式有POST、PUT、PATCH、DELETE。 ##### ##### Django默认开启了CSRF防护,会对上述请求方式进行CSRF防护验证,在测试时可以关闭CSRF防护机制,方法为在settings.py文件中注释掉CSRF中间件 ##### #### ①表单数据 #### 表单数据的获取通过request.POST返回的Query Dict对象来获取 注意:request.POST只能用来获取POST方式的请求体表单数据。 方法:request.POST.get()和request.POST.getlist() 如: 1. defget\_body(request): 2. a = request.POST.get( 'a') 3. b = request.POST.get( 'b') 4. alist = request.POST.getlist( 'a') 5. print(a) 6. print(b) 7. print(alist) 8. return HttpResponse( 'OK') #### ②非表单数据 #### 非表单类型的请求体数据,Django无法自动解析,可以通过request.body属性获取最原始的请求体数据,自己按照请求体格式(JSON、XML等)进行解析。 request.body返回bytes类型。 例如要获取请求体中的如下JSON数据 \{"name": "fenghua", "age": 24\} 方法:因为获取到的是原始二进制数据,要进行解码(字符串化,得到json数据),json\_dict化(将json数据转换成字典) 例如: 1. import json 2. 3. defget\_body\_json(request): 4. json\_str = request.body 5. json\_str = json\_str.decode() *\# python3.6 无需执行此步* 6. req\_data = json.loads(json\_str) 7. print(req\_data\[ 'name'\]) 8. print(req\_data\[ 'age'\]) 9. return HttpResponse( 'OK') ### 4.请求头里边的数据 ### ## ## 可以通过request.META属性获取请求头headers中的数据,request.META为字典类型。 常见的请求头如: CONTENT\_LENGTH – The length of the request body (as a string). CONTENT\_TYPE – The MIME type of the request body. HTTP\_ACCEPT – Acceptable content types for the response. HTTP\_ACCEPT\_ENCODING – Acceptable encodings for the response. HTTP\_ACCEPT\_LANGUAGE – Acceptable languages for the response. HTTP\_HOST – The HTTP Host header sent by the client. HTTP\_REFERER – The referring page, if any. HTTP\_USER\_AGENT – The client’s user-agent string. QUERY\_STRING – The query string, as a single (unparsed) string. REMOTE\_ADDR – The IP address of the client. REMOTE\_HOST – The hostname of the client. REMOTE\_USER – The user authenticated by the Web server, if any. REQUEST\_METHOD – A string such as "GET" or "POST". SERVER\_NAME – The hostname of the server. SERVER\_PORT – The port of the server (as a string). 方法: def get\_headers(request): print(request.META\['REQUEST\_METHOD'\]) return HttpResponse('haha') ### 5.其他常用请求对象 ### ## ## ## ## method:一个字符串,表示请求使用的HTTP方法,常用值包括:'GET'、'POST'。 user:请求的用户对象。 path:一个字符串,表示请求的页面的完整路径,不包含域名和参数部分。 encoding:一个字符串,表示提交的数据的编码方式。 如果为None则表示使用浏览器的默认设置,一般为utf-8。 这个属性是可写的,可以通过修改它来修改访问表单数据使用的编码,接下来对属性的任何访问将使用新的encoding值。 FILES:一个类似于字典的对象,包含所有的上传文件。 ## 二.响应response ## 响应的常见类型: HttpResponse, HttpResponse子类(如HttpResponseNotFound 404), JsonResponse, redirect重定向, render ### 1.HttpResponse ### 响应头的添加:得使用响应对象 response = HttpResponse() response\['name'\] = ‘fenghua' 响应体的添加: 方式1:直接返回 return HttpResponse(content=响应体, content\_type=响应体数据类型, status=状态码) 方式2:构造响应对象 response = HttpResponse(响应体) response.status\_code = 状态码 return response ### 2.HttpResponse子类 ### \# 直接返回404错误状态码 def http\_response(request): return HttpResponseNotFound(响应体内容) \# 返回的状态码自动设置成404,并显示前端显示的数据 ### 3.JsonResponse ### 返回json格式数据,并将响应头的Content-Type设置成application/json \# 响应json数据到前端 def response\_json(request): data\_json = \{"name": "fenghua", "age": 24\} \# 默认把json\_dict转成了json字符串 \# 再默认把json字符串转成二进制的json字符串 \# 默认将数据类型指定为 application/json return JsonResponse(data\_json) ### 4.redirect重定向 ### 反向解析reverse:根据路由名称或者命名空间解析出url路径 反向解析:要是命名空间是以分离的方式:url(r'^users/', include('users.urls', namespace='users111')) url(r'^index/$', views.index, name='index111') 则reverse方式为:reverse('users111:index111') 或者:reverse('users:index') 要是以一次性在主url写好的方式:url(r'^users/feng', views.feng, name='feng') 则reverse方式为:reverse('feng') redirect:根据反向解析出来的路径进行重定向 具体使用如下: \# 需求:访问'response\_redirect/'重定向到 'users.index' def response\_redirect(request): \# url(r'^users/', include('users.urls', namespace='users111')) \# url(r'^index/$', views.index, name='index111') return redirect(reverse('users:index')) \# redirect(reverse('users111:index111')) 也可以实现 ### 5.render返回模板 ### 用法: render(request对象, 模板文件路径, 模板数据字典) 1. from django.shortcuts import render 2. 3. defindex(request): 4. context=\{ 'city': '北京'\} 5. return render(request, 'index.html',context)
还没有评论,来说两句吧...