简体   繁体   English

如何反序列化base64编码的数据并将其与DRF一起使用

[英]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. 您应该decodeb64decode返回的字节字符串,然后将其传递给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.

相关问题 如何在 AppEngine 中存储 base64 编码的图像? - How do I store a base64-encoded image in AppEngine? 如何在Python中播放base64编码的声音 - How to play base64-encoded sound in Python 如何将 Base64DataURL 转换为 base64 编码的图像字节 - How to convert Base64DataURL to base64-encoded image bytes python:无效的base64编码字符串:数据字符数(5)不能比4的倍数多1 - python: Invalid base64-encoded string: number of data characters (5) cannot be 1 more than a multiple of 4 无效的 base64 编码字符串:数据字符数不能是 4 的倍数以上 1 - Invalid base64-encoded string: number of data characters cannot be 1 more than a multiple of 4 如何从发布的base64编码图像创建MongoDB / mongoengine ImageField? - How to Create a MongoDB/mongoengine ImageField from POSTed base64-encoded image? 如何在不写入磁盘的情况下将 numpy 数组编码为 base64 编码的 PNG? - How do I encode a numpy array to a base64-encoded PNG without writing to disk? 将base64编码的字符串转换为十六进制int - Convert base64-encoded string into hex int PEM 格式的 base64 编码公钥的序列化 - Serialization of a base64-encoded public key in PEM format 在ReportLab生成的PDF中包含base64编码的图像 - Including base64-encoded image in ReportLab-generated PDF
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM