python - 通过 Django Rest 发送文件

标签 python django django-rest-framework storage

我需要从不同的对象存储桶下载图像对象,并通过 Django Rest Framework 将其发送给用户。

我有这样的东西:

if request.method == 'GET':

    # Get object using swiftclient
    conn = swiftclient.client.Connection(**credentials)
    container, file = 'container_name', 'object_name'
    _, data = conn.get_object(container, file)

    # Send object to the browser
    return Response(data, content_type="image/png")

data 变量包含字节类型。

测试时我收到错误: 'utf-8' 编解码器无法解码位置 0 中的字节 0x89:无效的起始字节

有什么办法可以解决这个问题?

最佳答案

如果您希望通过 Django Rest Framework 直接将图像传递给用户,使用 HttpResponse 可能更合适。

from django.http import HttpResponse

return HttpResponse(data, content_type="image/png")

Django Rest Framework 自己的 Response 将尝试呈现二进制数据,这可能会导致您看到的编码问题。

关于python - 通过 Django Rest 发送文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49447263/

相关文章:

Django REST 框架 - 要求 BooleanField 为真

python - 在 Pandas 中合并两行(一个有值,另一个为 NaN)

Python 前导下划线_variables

python - NoReverseMatch 与 Python 社交身份验证/Facebook 登录

python - 尝试传递字符串以通过 Django Rest Framework url 进行查询

python - 在设置 View 集时,出现错误 AttributeError : 'function' object has no attribute 'get_extra_actions'

python - 当我使用调试版本的 Python 时如何使用 gdb?

Python Pandas : remove entries based on the number of occurrences

python - Django Rest Framework 在后台从模型中导出 csv 数据

python - 405 “Method POST is not allowed” 在 Django REST 框架中