在写django view时,对于view中的request参数一直都模棱两可的,总是通过一次次尝试才能和前端友好的传递参数,故总结了一下request获取参数的一些常见情况
- post data/get params :dict类型
test:
#content_type:text/plain
import requests
requests.get('https://~', params={'id': '1234560'}) #GET参数实例
requests.post('http://~', data={'name': 'hayley'}) #POST参数实例
django:
def get(self,request):
#GET : <QueryDict: {'id': ['1234560']}>
#request.body : b''
id=request.GET.get('id')
#……
def post(self,request):
#request.POST : <QueryDict: {'name': ['hayley']}>
#request.body : b'name=hayley'
id=request.POST.get('name')
#……
- post data :str类型
test:
import requests
import json
r = requests.post('http://~', data=json.dumps({'saytext': 'hello world'}))
django:
#content_type:application/json
def post(self,request):
#request.body : b'{"saytext": "hello world"}'
text=request.body #bytes
#……
- multipart/form-data FILES
test:
#指定 Content-Type: multipart/form-data;
url = " http://~"
#files = {'file':('test10.mp4', open(FILE_PATH, 'rb'), 'multipart/form-data')}
with open(FILE_PATH, 'rb') as fb:
files = {'file': ('test10.mp4', fb, 'multipart/form-data')}
response = requests.post(url, files=files,data={})
print(response.text)
django:
#指定 Content-Type: multipart/form-data;
#文件:Content-Disposition: form-data; name="file"; filename="test10.mp4" Content-Type: video/mp4
#参数:Content-Disposition: form-data; name="vid"
def post(self,request):
#POST : <QueryDict: {'vid': ['1234567890']}>
vid=request.POST.get('vid')
# FILES : <MultiValueDict: {'file': [<InMemoryUploadedFile: test10.mp4 (video/mp4)>]}>
f=request.FILES.get('file')
#……
参考
python第三方库requests详解
https://www.cnblogs.com/mrchige/p/6409444.html