django 请求解析器-前端请求参数解析
原创
©著作权归作者所有:来自51CTO博客作者wx5b6d6c951e615的原创作品,请联系作者获取转载授权,否则将追究法律责任
django rest framework 请求参数解析
from django.core.handlers.wsgi import WSGIRequest
如果满足是 post请求而且
第一请求头满足
self.content_type == 'application/x-www-form-urlencoded'QueryDict(self.body, encoding=self._encoding), MultiValueDict() 的request.body才有数值
第二:其次数据格式也有要求:a=33&b=000088
restframework 解析器:
body is .... b'test=222&ke=vvv&ke=222'
request.data is <QueryDict: {'test': ['222'], 'ke': ['vvv', '222']}>
request.POST is <QueryDict: {'test': ['222'], 'ke': ['vvv', '222']}>
{'test': ['222'], 'ke': ['vvv', '222']}
setting.py 配置全局解析器:
"DEFAULT_PARSER_CLASSES":["rest_framework.parsers.JSONParser","rest_framework.parsers.FormParser"]
示范:
REST_FRAMEWORK={
"versioning_class":"rest_framework.versioning.URLPathVersioning",
"DEFAULT_VERSION":"v1",
"ALLOWED_VERSIONS":["v1","v2"],
"VERSION_PARAM":"version",
"DEFAULT_PARSER_CLASSES":["rest_framework.parsers.JSONParser","rest_framework.parsers.FormParser"]
}
关于 request.FILES对象的方法:
print('request.body', request.body) # 这个读取要放在data前不然报错
data=request.data
file=request.FILES.get('file')
print('file.getlist',request.FILES.getlist(key='excel'))
print('file.data',request.data)
print('file.name',file.name)
print('file.size',file.size)
print('file.content_type',file.content_type)
print('file.read()',file.read())
print('request.post',request.POST)
打印如下:
file.body \x00\x00\x00IEND\xaeB`\x82\r\n------WebKitFormBoundarysQS0FjZeur1FcOCZ\r\nContent-Disposition: form-data; name="username"\r\n\r\nzhangsan\r\n------WebKi
tFormBoundarysQS0FjZeur1FcOCZ\r\nContent-Disposition: form-data; name="password"\r\n\r\n123456\r\n------WebKitFormBoundarysQS0FjZeur1FcOCZ--\r\n'
file.getlist [<InMemoryUploadedFile: 批量添加实物发货单(2020-11-11).xlsx (application/vnd.openxmlformats-officedocument.spreadsheetml.sheet)>]
file.data <QueryDict: {'name': ['1'], 'file': [<InMemoryUploadedFile: hello.png (image/png)>]}>
file.name hello.png
file.size 38739
file.content_type image/png
request.post <QueryDict: {'username': ['zhangsan'], 'password': ['123456']}>