0
点赞
收藏
分享

微信扫一扫

Django视图之HttpRequest对象和HttpResponse对象


HttpRequest对象

回想一下,利用HTTP协议向服务器传参有几种途径?

  • 提取URL的特定部分,如/weather/beijing/2018,可以在服务器端的路由中用正则表达式截取;
  • 查询字符串(query string),形如key1=value1&key2=value2;
  • 请求体(body)中发送的数据,比如表单数据、json、xml;
  • 在http报文的头(header)中。

1 URL路径参数

  • 如果想从URL中获取值​​http://127.0.0.1:8000/18/188/​
  • 应用中​​urls.py​

from django.urls import path
from book.views import goods
urlpatterns = [
path('<cat_id>/<goods_id>/',goods)
]

  • 视图中函数: 参数的位置不能错

from django.http import JsonResponse
def goods(request,cat_id,id):

return JsonResponse({'cat_id':cat_id,'id':id})

2 Django中的QueryDict对象

HttpRequest对象的属性GET、POST都是QueryDict类型的对象

与python字典不同,QueryDict类型的对象用来处理同一个键带有多个值的情况

  • 方法get():根据键获取值
    如果一个键同时拥有多个值将获取最后一个值
    如果键不存在则返回None值,可以设置默认值进行后续处理

get('键',默认值)

  • 方法getlist():根据键获取值,值以列表返回,可以获取指定键的所有值
    如果键不存在则返回空列表[],可以设置默认值进行后续处理

getlist('键',默认值)

3. 查询字符串Query String

获取请求路径中的查询字符串参数(形如?k1=v1&k2=v2),可以通过request.GET属性获取,返回QueryDict对象。

# /get/?a=1&b=2&a=3

def get(request):
a = request.GET.get('a')
b = request.GET.get('b')
alist = request.GET.getlist('a')
print(a) # 3
print(b) # 2
print(alist) # ['1', '3']
return HttpResponse('OK')

重要:查询字符串不区分请求方式,即假使客户端进行POST方式的请求,依然可以通过request.GET获取请求中的查询字符串数据。

4 请求体

请求体数据格式不固定,可以是表单类型字符串,可以是JSON字符串,可以是XML字符串,应区别对待。

可以发送请求体数据的请求方式有POSTPUTPATCHDELETE

Django默认开启了CSRF防护,会对上述请求方式进行CSRF防护验证,在测试时可以关闭CSRF防护机制,方法为在settings.py文件中注释掉CSRF中间件,如:

Django视图之HttpRequest对象和HttpResponse对象_python

 

4.1 表单类型 Form Data

前端发送的表单类型的请求体数据,可以通过request.POST属性获取,返回QueryDict对象。

def post(request):
a = request.POST.get('a')
b = request.POST.get('b')
alist = request.POST.getlist('a')
print(a)
print(b)
print(alist)
return HttpResponse('OK')

4.2 非表单类型 Non-Form Data

非表单类型的请求体数据,Django无法自动解析,可以通过request.body属性获取最原始的请求体数据,自己按照请求体格式(JSON、XML等)进行解析。request.body返回bytes类型。

例如要获取请求体中的如下JSON数据

{"a": 1, "b": 2}

可以进行如下方法操作:

import json

def post_json(request):
json_str = request.body
json_str = json_str.decode() # python3.6 无需执行此步
req_data = json.loads(json_str)
print(req_data['a'])
print(req_data['b'])
return HttpResponse('OK')

5.验证path中路径参数

系统为我们提供了一些路由转换器位置在​​django.urls.converters.py​

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

我们可以通过以下形式来验证数据的类型

path('<int:cat_id>/<int:id>/',goods),

自定义转换器

​http://127.0.0.1:8000/18500001111/​​默认的路由转换器中,没有专门用来匹配手机号的路由转换器。所以在使用path()实现需求时,就无法直接使用默认的路由转换器。如果默认的路由转换器无法满足需求时,我们就需要自定义路由转换器。在任意可以被导入的python文件中,都可以自定义路由转换器。

  • 比如:在工程根目录下,新建​​converters.py​​文件,用于自定义路由转换器

class MobileConverter:
"""自定义路由转换器:匹配手机号"""
# 匹配手机号码的正则
regex = '1[3-9]\d{9}'

def to_python(self, value):
# 将匹配结果传递到视图内部时使用
return int(value)

def to_url(self, value):
# 将匹配结果用于反向解析传值时使用
return str(value)

  • 注册自定义路由转换器
  • 在总路由中,注册自定义路由转换器

from django.urls import register_converter
# 注册自定义路由转换器
# register_converter(自定义路由转换器, '别名')
register_converter(MobileConverter, 'mobile')

urlpatterns = []

  • 使用自定义路由转换器

# 测试path()中自定义路由转换器提取路径参数:手机号 http://127.0.0.1:8000/18500001111/
path('<mobile:phone>/',register)

6 请求头

可以通过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['CONTENT_TYPE'])
return HttpResponse('OK')

7 其他常用HttpRequest对象属性

  • method:一个字符串,表示请求使用的HTTP方法,常用值包括:'GET'、'POST'。
  • user:请求的用户对象。
  • path:一个字符串,表示请求的页面的完整路径,不包含域名和参数部分。
  • encoding:一个字符串,表示提交的数据的编码方式。
  • 如果为None则表示使用浏览器的默认设置,一般为utf-8。
  • 这个属性是可写的,可以通过修改它来修改访问表单数据使用的编码,接下来对属性的任何访问将使用新的encoding值。
  • FILES:一个类似于字典的对象,包含所有的上传文件。

HttpResponse对象

视图在接收请求并处理后,必须返回HttpResponse对象或子对象。HttpRequest对象由Django创建,HttpResponse对象由开发人员创建。

1 HttpResponse

可以使用django.http.HttpResponse来构造响应对象。

HttpResponse(content=响应体, content_type=响应体数据类型, status=状态码)

也可通过HttpResponse对象属性来设置响应体、响应体数据类型、状态码:

  • content:表示返回的内容。
  • status_code:返回的HTTP响应状态码。

响应头可以直接将HttpResponse对象当做字典进行响应头键值对的设置:

response = HttpResponse()
response['itcast'] = 'Python' # 自定义响应头Itcast, 值为Python

示例:

from django.http import HttpResponse

def response(request):
return HttpResponse('itcast python', status=400)
或者
response = HttpResponse('itcast python')
response.status_code = 400
response['itcast'] = 'Python'
return response

2 HttpResponse子类

Django提供了一系列HttpResponse的子类,可以快速设置状态码

  • HttpResponseRedirect 301
  • HttpResponsePermanentRedirect 302
  • HttpResponseNotModified 304
  • HttpResponseBadRequest 400
  • HttpResponseNotFound 404
  • HttpResponseForbidden 403
  • HttpResponseNotAllowed 405
  • HttpResponseGone 410
  • HttpResponseServerError 500

3 JsonResponse

若要返回json数据,可以使用JsonResponse来构造响应对象,作用:

  • 帮助我们将数据转换为json字符串
  • 设置响应头Content-Typeapplication/json

from django.http import JsonResponse

def response(request):
return JsonResponse({'city': 'beijing', 'subject': 'python'})

4 redirect重定向

from django.shortcuts import redirect

def response(request):
return redirect('/get_header')

举报

相关推荐

0 条评论