[英]How to deserialize base64-encoded data and use it with DRF
My goal is to come up with an endpoint that gets a base64-decoded string. 我的目标是提出一个获取base64解码的字符串的端点。 This is based described by an example 这是基于一个示例描述的
My input JSON looks like this: 我的输入JSON如下所示:
{
"encoded_data": "a2F0aWUsIGpvaG5zLCBrYXRpZUBnbWFpbC5jb20KdG9tbXksbGVlLHRvbW15QGdtYWlsLmNvbQ=="
}
I have tried to implement it the following way, but I end up with the following error message: 我尝试通过以下方式实现它,但最终出现以下错误消息:
JSON parse error - Expecting value: line 1 column 1 (char 0)
Looks like I've messed up the concepts. 看来我搞砸了这些概念。 Really need help on this: 确实需要帮助:
class UsersFileUpload(APIView):
#parser_classes = (MultiPartParser,)
def post(self, request):
stream = base64.b64decode(request.data['encoded_data'])
stream = io.BytesIO(stream)
data = JSONParser().parse(stream)
serializer = UsersSerializer(data=data)
if serializer.is_valid():
serializer.save()
return Response(serializer.data)
return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
I don't think you're decoding your text correctly, you shouldn't need to use BytesIO
. 我认为您无法正确解码文本,不需要使用BytesIO
。
You should decode
the byte string returned from b64decode
and then pass it to the JSONParser. 您应该decode
从b64decode
返回的字节字符串,然后将其传递给JSONParser。
b64decoded_data = base64.b64decode(request.data['encoded_data']).decode('UTF-8')
data = JSONParser().parse(b64decoded_data)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.