【问题标题】:Django rest framework ApiView reurn executable fileDjango rest 框架 ApiView reurn 可执行文件
【发布时间】:2018-07-21 18:56:39
【问题描述】:

类似的问题 django rest framework return file

尝试应用类似的解决方案在 Django Rest ApiView 中返回一个可执行的 python 二进制文件:

from wsgiref.util import FileWrapper

bin_file = open(f'cli/builds/dist/cli', 'rb')
response = Response(FileWrapper(bin_file), content_type='application/octet-stream')
response['Content-Disposition'] = f'attachment; filename="cli"'
response.status_code = status.HTTP_200_OK
return response

得到Object of type 'FileWrapper' is not JSON serializable 错误。 参考前面提到的 SO 主题 - 这个解决方案正在为一个 zip 文件工作。

问题 - 为什么它不适用于我的设置,返回 python 可执行文件?

python 3.6.5, djangorestframework==3.8.2

尝试了ResponseHttpResponse

【问题讨论】:

    标签: python django python-3.x django-rest-framework


    【解决方案1】:

    尝试使用 HttpResponse 代替 DRF 的 Response

    from wsgiref.util import FileWrapper
    from django.http.response import HttpResponse
    
    bin_file = open(f'cli/builds/dist/cli', 'rb')
    response = HttpResponse(FileWrapper(bin_file), content_type='application/octet-stream')
    response['Content-Disposition'] = f'attachment; filename="cli"'
    response.status_code = status.HTTP_200_OK
    return response

    【讨论】:

    • 如果您使用 HttpResponse,您将不会收到 Object of type 'FileWrapper' is not JSON serializable 错误。 (我自己试过这个解决方案,效果很好)
    • 嘿,谢谢,我明白了。我使用来自django.httpHttpResponse 而不是来自django.http.response。好像他们不一样。典型的盲目错误:D
    • 快乐编码:)
    猜你喜欢
    • 2016-06-20
    • 2021-01-16
    • 1970-01-01
    • 2022-08-14
    • 2020-05-06
    • 2017-01-04
    • 2017-07-07
    • 2021-10-30
    • 1970-01-01
    相关资源
    最近更新 更多