将django请求的.body(字节)转换为json

bksxznpy  于 2023-04-13  发布在  Go
关注(0)|答案(3)|浏览(267)

我有一个基于类的视图,其中有一个put函数,并试图将request.body导入json。

from django.views import View
import json
class StudentView(View):
    def put(self, request):
        body = request.body #b'name=Arpita+kumari+Verma&roll=109&city=USA'
        json_body = json.loads(body) # JSONError 'expecting dict values but given bytes object'
        # I want something like this
        # {
        #      'name':'Arpita kumari Verma',
        #      'roll':109,
        #      'city':'USA',
        # }
        json_dumped_data = json.dumps(json_body)
        return HttpResponse(json_dumped_data, content_type="application/json")

我的请求app

url = 'http://127.0.0.1:8000/api/student/'
json_data = {
    'name':'Arpita kumari Verma',
    'roll':109,
    'city':'USA'
}
results = requests.put(url, json_data)
4ioopgfo

4ioopgfo1#

这是因为在requests.put中你不是发送json,而是发送表单数据。你可以在requests.put中发送json,或者将request.body转换为QueryDict,然后做类似的事情:
json.dumps(dict(QueryDict(request.body)))

zz2j4svz

zz2j4svz2#

我有解决办法

json_data_recieved = request.POST
# this method can be used in every request methods (post, put, patch, delete)
# except get (user request.GET for get methods)
knsnq2tg

knsnq2tg3#

只是替换

body = request.body
json_body = json.loads(body)

body_unicode = request.body.decode('utf-8')
json_body = json.loads(body_unicode)

相关问题