Python 用魔杖读写上传文件

Python 用魔杖读写上传文件,python,django,django-rest-framework,imagemagick,wand,Python,Django,Django Rest Framework,Imagemagick,Wand,这是我的密码: class ToPng(APIView): def post(self, request, *args, **kwargs): revision = request.data.get('revision', None) file = request.data.get('file', None) with tempfile.TemporaryFile() as tmp: tmp.write(file

这是我的密码:

class ToPng(APIView):
    def post(self, request, *args, **kwargs):

        revision = request.data.get('revision', None)
        file = request.data.get('file', None)

        with tempfile.TemporaryFile() as tmp:
            tmp.write(file.read())
            all_pages = Image(file=tmp)
            single_image = all_pages.sequence[0]
            with Image(single_image) as img:
                img.format = 'png'
                img.background_color = Color('white')
                img.alpha_channel = 'remove'
                MyModel.objects.create(revision=revision, file=img)
                return Response(HTTP_200_OK)
我得到一个错误:“此图像格式没有解码委托”`@error/blob.c/BlobToImage/353”


显然,我犯了一个严重的错误,因为安装了imagemagick和ghostscript的wand可以立即将Pdf转换为Png。我可能读错了,但我不知道还能做什么。

在读取之前,只需将tempfile重置回文件的开头即可

使用tempfile.TemporaryFile()作为tmp的
:
tmp.write(file.read())
tmp.seek(0)
所有页面=图像(文件=tmp)
已更新

我已经几年没有使用视图了,但是您应该能够使用
StringIO
在memoryUploadedFile中创建
。来自

导入StringIO
# ... 在完成img工作后跳到。。。
img_io=StringIO.StringIO()
保存(文件=img\u io)
img_file=InMemoryUploadedFile(img_io,
没有一个
“first_page.jpg”,
“图像/jpeg”,
伊姆格·伊奥·伦,
(无)
MyModel.objects.create(revision=revision,file=img\u文件)

非常感谢您。现在我可以把它转换成魔杖图像。但我无法拯救它。它说文件没有提交。有什么想法吗?我不想存储它,所以我应该将它转换回InMemoryUploadedFile吗?就是这样。你真了不起,伙计。祝你度过愉快的一天:)之间有一条线,供参考:img.save(img_io)