简体   繁体   English

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

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

As it says in the title, I am trying to upload a model.pkl and save it in an API made in django.正如标题中所说,我正在尝试上传 model.pkl 并将其保存在 django 制造的 API 中。 I manage to save the model.pkl correctly in the API, however the file is uploaded in a corrupt way, because I cannot read the pickle file.我设法将 model.pkl 正确保存在 API 中,但是文件以损坏的方式上传,因为我无法读取泡菜文件。

Im open to any solutions that can make the pickle file be uploaded, stored and readed in the API.我愿意接受任何可以在 API 中上传、存储和读取泡菜文件的解决方案。

Class to upload the file and save it 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)

Error when reading the file读取文件时出错

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

Im new in this, please before voting down, tell me how do you think I can improve the question to get an accurate solution.我是新手,请在投票之前告诉我您认为我可以如何改进问题以获得准确的解决方案。

Postman Postman

在此处输入图像描述 在此处输入图像描述

When using FileUploadParser the entire body of the request should be the file contents, don't send the file as form data.使用FileUploadParser时,请求的整个主体应该是文件内容,不要将文件作为表单数据发送。

To do this in Postman, select "binary" as the data type instead of "form-data" and select your file there为此,请在 Postman、select “二进制”而不是“表单数据”和 select 作为数据类型中执行此操作

在此处输入图像描述

To set the filename you need to set a header "Content-Disposition" and pass attachment; filename=<your_filename.ext>要设置文件名,您需要设置 header "Content-Disposition" 并传递attachment; filename=<your_filename.ext> attachment; filename=<your_filename.ext>

在此处输入图像描述

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM