TemporaryUploadedFile类型的对象不可进行JSON序列化



我正试图在Django中将我的文件上传视图作为一项任务使用芹菜来运行,除了当图像文件超过2.5MB时,其他操作都很好,芹菜抱怨它无法序列化。我使用芹菜的原因是,我想从每个文件上传任务中获得进度信息,并从中创建一个进度条。下面是我的代码。

/views.py
def simple_upload(request):
if request.method == 'POST' and request.FILES['image']:
file = request.FILES['image']
#process_download(file)
task = process_download.delay(file)
#print(task.task_id)
return redirect('index')
return render(request, 'upload.html')
@shared_task(bind=True)
def process_download(self, image_file):
process_recoder = ProgressRecorder(self)
print('Upload: Task Started')
# time.sleep(50)
fs = FileSystemStorage()
buffer = io.BytesIO()
chunk_size = 0
for chunk in image_file.chunks():
chunk_size += sys.getsizeof(chunk)
buffer.write(chunk)
process_recoder.set_progress(chunk_size, image_file.size)
buffer.seek(0)
image = ImageFile(buffer, name=image_file.name)
fs.save(image_file.name, image)
return 'Done'

有没有什么方法可以让芹菜序列化大于2.5的图像,使用Django设置FILE_UPLOAD_MAX_MEMORY_SIZE = 50*1024*1024也不起作用?

您可以将此图像文件存储在应用程序的Model中。然后,您可以将此模型的id字段传递给Celery任务,这是可以保证的。

在Celery任务中,您将负责从模型中获取图像文件,然后完成您的工作。

你的观点会变成:

def simple_upload(request):
if request.method == 'POST' and request.FILES['image']:
file = request.FILES['image']
image_upload = ImageUpload.objects.create(file=file)
task = process_download.delay(image_upload.id)
return redirect('index')
return render(request, 'upload.html')

你的芹菜任务:

@shared_task(bind=True)
def process_download(self, image_upload_id):
image_file = ImageUpload.objects.get(id=image_upload_id).file
process_recoder = ProgressRecorder(self)
print('Upload: Task Started')
# time.sleep(50)
fs = FileSystemStorage()
buffer = io.BytesIO()
chunk_size = 0
for chunk in image_file.chunks():
chunk_size += sys.getsizeof(chunk)
buffer.write(chunk)
process_recoder.set_progress(chunk_size, image_file.size)
buffer.seek(0)
image = ImageFile(buffer, name=image_file.name)
fs.save(image_file.name, image)
return 'Done'

相关内容

  • 没有找到相关文章

最新更新