我试图创建一种方法来上传xlsx文件,然后使用芹菜执行一些操作。
我在想:
我想做这样的事:
class ImportMyFileView(APIView):
    parser_classes = (FileUploadParser, )
    def post(self, request, filename, format=None):
        my_file = request.data["file"]
        with open(f"/tmp/{my_file.name}", "wb+") as destination:
            for chunk in my_file.chunks():
                destination.write(chunk)
        # call_celery_here()
        ...
        Return something我可以在我想要的地方生成文件,但问题是当我打开xlsx时。我在这里得到了这个:
--X-INSOMNIA-BOUNDARY
Content-Disposition: form-data
Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet
PK<q^Q_rels/.rels���J1��}��{w�Dd���ЛH}���a7�0u}{�Z���I~��7C��f�G�Fo�Z+���{�����kW�#�VJ$cʪ��l� �n�0�\Q�X^:�`���d�d{�m]_�d����h��V����F�w�^F9��W��-�(F/3�O�DSU�N�l/w�{N(�[��q��T����u<��r�?焮�s9�F����M��h���'h?PKf����有什么细节遗漏吗?
发布于 2020-11-05 19:51:13
以下是我将如何做到这一点,依赖于DRF内置的功能:
import os
from rest_framework import serializers
from django.core.files.storage import FileSystemStorage
class UploadSerializer(serializers.Serializer):
    file = serializers.FileField()
class UploadView(APIView):
    ...
    def post(self, request):
        ser = UploadSerializer(request.data)
        ser.is_valid(raise_exception=True)
        fs = FileSystemStorage(tempfile.gettempdir())
        file_name = fs.save(content=ser.validated_data['file'])
        full_path = os.path.join(fs.location, file_name)
        celery_func.delay(file_name=full_path)
        return Response("Upload OK")要做到这一点,一个更健壮的方法是创建一个表示要处理的上载的模型,并使用django模型的FileField。
class Todo(models.Model):
   xlsx_file = models.FileField(...) # read the docs on this
   created_at = models.DateTimeField(auto_now_add=True)
   is_complete = models.BooleanField(default=False)
class UploadView(APIView):
    def post(self, request):
       ...
       todo = Todo.objects.create(
           xslx_file = ser.validated_data['file']
       )
       celery_func.delay(todo_id=todo.pk)
       return Response("Upload OK")一旦成功,您就可以单独使用ModelSerializer,或者与ModelViewSet配对使用。不过,这是一个更大的学习曲线。
https://stackoverflow.com/questions/64703354
复制相似问题