Django Rest框架:空的request.data [英] Django Rest Framework: empty request.data
本文介绍了Django Rest框架:空的request.data的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有以下DRF视图代码:
I have the following code for a view of DRF:
from rest_framework import viewsets
class MyViewSet(viewsets.ViewSet):
def update(self, request, pk = None):
print pk
print request.data
我通过 python请求通过以下方式调用URL:
I call the URL via python-requests in the following way:
import requests
payload = {"foo":"bar"}
headers = {'Content-type': 'application/json'}
r = requests.put("https://.../myPk", data= payload, headers=headers)
但是当从服务器接收到请求时,request.data为空。这里有输出:
but when the request is received from the server, request.data is empty. Here there is the output:
myPk
<QueryDict: {}>
如何解决这个问题?
推荐答案
您需要将有效负载
作为序列化的 json
对象发送。 / p>
You need to send the payload
as a serialized json
object.
import json
import requests
payload = {"foo":"bar"}
headers = {'Content-type': 'application/json'}
r = requests.put("https://.../myPk/", data=json.dumps(payload), headers=headers)
否则会发生什么是DRF实际上会抱怨:
Otherwise what happens is that DRF will actually complain about:
*** ParseError: JSON parse error - No JSON object could be decoded
您将通过调试视图来看到该错误消息(例如,使用 pdb 或 ipdb )或打印如下变量:
You would see that error message by debugging the view (e.g. with pdb or ipdb) or printing the variable like this:
def update(self, request, pk = None):
print pk
print str(request.data)
这篇关于Django Rest框架:空的request.data的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文