【问题标题】:How to upload and save a pickle file to a django rest framework?如何将pickle文件上传并保存到django rest框架?
【发布时间】:2022-01-10 19:20:42
【问题描述】:

正如标题中所说,我正在尝试上传 model.pkl 并将其保存在 django 制作的 API 中。 我设法在 API 中正确保存了 model.pkl,但是文件以损坏的方式上传,因为我无法读取 pickle 文件。

我对任何可以在 API 中上传、存储和读取泡菜文件的解决方案持开放态度。

上传文件并保存的类

class FileUploadView(APIView):
    parser_classes = (FileUploadParser,)

    def put(self, request):
        file = request.data.get('file', None)
        file_name = f'path/{file.name}'

        path = default_storage.save(name=file_name, content=ContentFile(file.read()))
        tmp_file = os.path.join(settings.MEDIA_ROOT, path)

        if file is not None:
            return Response(f'File: {file.name} successfully uploaded and saved!', status=HTTP_200_OK)
        else:
            return Response(f'File not found!', status=HTTP_400_BAD_REQUEST)

读取文件时出错

def read_PickleModel(path_to_PickleModel):
    with open(path_to_PickleModel, 'rb') as f:
        pickle_model = pickle.load(f)
    return pickle_model

read_PickleModel(path_to_PickleModel)

Traceback:
DEBUG: An exception has ocurred: invalid load key, '-'.

邮递员

【问题讨论】:

  • 你能展示一下原始的pickle是如何生成的,它肯定没有损坏吗?
  • @IainShelvington 肯定没有损坏,我之前测试过。当我上传并存储在 API 中时它已损坏
  • @IainShelvington 当我在 colab 笔记本中阅读泡菜模型时,它可以正常工作。我也尝试了不同的 model.pkl 并且是相同的情况。
  • 您能否在您的视图中展示您如何发送/生成泡菜以及print(file.content_type, file.charset) 的输出?
  • 这里是打印:multipart/form-data;边界=--------------167993137263431154392844 utf-8

标签: python django django-rest-framework postman pickle


【解决方案1】:

使用FileUploadParser时,请求的整个正文应该是文件内容,不要将文件作为表单数据发送。

要在 Postman 中执行此操作,请选择“二进制”作为数据类型而不是“表单数据”,然后在此处选择您的文件

要设置文件名,您需要设置标题“Content-Disposition”并传递attachment; filename=<your_filename.ext>

【讨论】:

    猜你喜欢
    • 2015-10-04
    • 2013-12-26
    • 2016-10-25
    • 2018-01-27
    • 2022-10-13
    • 2020-06-17
    • 2016-02-16
    • 2021-09-27
    • 2019-07-23
    相关资源
    最近更新 更多