【问题标题】:Django Rest Framework function view post not workingDjango Rest Framework 功能视图帖子不起作用
【发布时间】:2018-07-13 18:22:15
【问题描述】:

所以我试图通过一个简单的 Django Rest 框架函数视图来提供一个静态文件。它给了我 200 个代码,但不下载文件。

代码如下:

@api_view(['POST'])
def download_file(request):

    if request.method == 'POST':
        serializer = MySerializer(data=request.data)
        filename = 'file.xlsx'
        file_full_path = "src/{0}".format(filename)

        with open(file_full_path, 'rb') as f:
            file = f.read()
        response = HttpResponse(file, content_type="application/xls")
        response['Content-Disposition'] = "attachment; filename={0}".format(filename)
        response['Content-Length'] = os.path.getsize(file_full_path)
        return response
    return Response(status=status.HTTP_400_BAD_REQUEST)

我在这里做错了什么?

【问题讨论】:

  • 您好,您的代码在 MySerializer 中运行良好检查:您需要这个吗?

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


【解决方案1】:

您正在尝试使用 HTTP POST 方法下载文件,我认为这不是一个好方法。因此,请尝试 HTTP GET 进行下载。如果您希望提供额外的参数(POST 方法中的有效负载),您可以使用 Query Parameter 作为 /api/end/point/?param=value1&param2=value2
所以,试试下面的sn-p,

@api_view(['GET'])
def download_file(request):
    if request.method == 'GET':
        filename = 'file.xlsx'
        file_full_path = "src/{0}".format(filename)

        with open(file_full_path, 'rb') as f:
            file = f.read()
        response = HttpResponse(file, content_type="application/xls")
        response['Content-Disposition'] = "attachment; filename={0}".format(filename)
        response['Content-Length'] = os.path.getsize(file_full_path)
        return response
    return Response(status=status.HTTP_400_BAD_REQUEST)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-07-15
    • 2019-09-15
    • 2014-09-21
    • 2021-05-23
    • 1970-01-01
    • 1970-01-01
    • 2013-12-25
    • 1970-01-01
    相关资源
    最近更新 更多