首页 文章

在django restframework中序列化数据

提问于
浏览
1

我通过Django restframework中的POST请求获得以下数据 . 我需要序列化这些数据,这些数据包含多个模型的数据 .

data={'admin-1':
    {'first_name':'john'
    ,'last_name':'white'
    ,'job_title':'CEO'
    ,'email':'test1@gmail.com'
    },
'admin-2':
    {'first_name':'lisa'
    ,'last_name':'markel'
    ,'job_title':'CEO'
    ,'email':'test2@gmail.com'
    },
'company-detail':{'description':'We are a renowned engineering company'
,'size':'1-10'
,'industry':'Engineering'
,'url':'http://try.com'
,'logo':''
,'addr1':'1280 wick ter'
,'addr2':'1600'
,'city':'rkville'
,'state':'md'
,'zip_cd':'12000'
,'phone_number_1':'408-393-254'
,'phone_number_2':'408-393-221'}

r = requests.post('http://127.0.0.1:8000/api/create-company-profile/',data=data)
print r.status_code
print r.text

这是CreateAPI视图 -

class CompanyCreateApiView(CreateAPIView):

    def post(self, request, *args, **kwargs):
        print 'request ==', request
        print 'request.data == ', request.data['admin-2']

        import json
        print json.loads(request.data)

        data=json.dumps({'status':'success'})
        return Response(data, status=status.HTTP_200_OK)

我基本上需要对数据进行反序列化,但会出现此错误 .

request == request.data == job_title内部服务器错误:/ api / create-company-profile / Traceback(最近一次调用最后一次):文件“/Users/prem/.virtualenvs/ghost/lib/python2.7/site -packages / django / core / handlers / base.py“,第111行,在get_response response = wrapped_callback(request,* callback_args,** callback_kwargs)File”/Users/prem/.virtualenvs/ghost/lib/python2.7/ site-packages / django / views / decorators / csrf.py“,第57行,在wrapped_view中返回view_func(* args,** kwargs)文件”/Users/prem/.virtualenvs/ghost/lib/python2.7/site- packages / django / views / generic / base.py“,第69行,在视图中返回self.dispatch(request,* args,** kwargs)File”/Users/prem/.virtualenvs/ghost/lib/python2.7/ site-packages / rest_framework / views.py“,第452行,在dispatch response中= self.handle_exception(exc)文件”/Users/prem/.virtualenvs/ghost/lib/python2.7/site-packages/rest_framework/views . py“,第449行,在dispatch响应中= handler(request,* args,** kwargs)文件”/ Users / prem / Documents / Ghost / positionmatch-new / m enkes-server-master / menkesserver / human_resources / views.py“,第81行,在post print json.loads(request.data)File”/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2 . 7 / json / init.py“,第338行,在load中返回_default_decoder.decode(s)文件”/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/json/decoder.py“ ,第365行,在解码obj中,end = self.raw_decode(s,idx = _w(s,0).end())TypeError:期望的字符串或缓冲区

1 回答

  • 0

    不需要在视图中手动解码POST数据 . 只要您使用 JSONParser ,如parsers documentation中所述, request.data 应该已经为您完全解析 .

    此外,您发送到视图的请求看起来可能不是您的想法 . 如果要使用请求发送JSON数据,则需要更加明确 . 如requests documentation中的示例所示:

    >>> import json
    >>> url = 'https://api.github.com/some/endpoint'
    >>> payload = {'some': 'data'}
    
    >>> r = requests.post(url, data=json.dumps(payload))
    

相关问题