如何将 pickle 文件上传并保存到 django rest 框架?

How to upload and save a pickle file to a django rest framework?

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

我愿意接受任何可以使 pickle 文件在 API 中上传、存储和读取的解决方案。

Class上传文件并保存

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, '-'.

邮递员

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

要在 Postman 中执行此操作,select“二进制”作为数据类型而不是“form-data”并且select您的文件在那里

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