这是我的创建功能:
def create(self,request,*args,**kwargs):
serializer = ArchiveSerializer( data = request.data, context = {"request":request} )
serializer.is_valid(raise_exception=True)
filename=serializer.validated_data.pop('file')
serializer.save()
id = serializer.validated_data.get("id")
save_file_in_background.delay(id,filename)
return Response(serializer.data, status=status.HTTP_201_CREATED)
这是tasks.py
from celery import shared_task
from django.core.files.base import ContentFile
from .models import Archive
@shared_task
def save_file_in_background(id,filename):
try:
archive = Archive.objects.get(pk=id)
if filename:
archive.file.save(filename, ContentFile(filename))
archive.save()
except Archive.DoesNotExist:
pass
但是当尝试添加对象并上传文件时出现此错误: TemporaryUploadedFile 类型的对象不可 JSON 序列化
除了在后台上传文件但出现此错误: “TemporaryUploadedFile 类型的对象不可 JSON 序列化”
您可以避免直接经过
TemporaryUploadedFile
1 - 在创建功能中临时保存文件:
def create(self, request, *args, **kwargs):
serializer = ArchiveSerializer(data=request.data)
serializer.is_valid(raise_exception=True)
serializer.save()
id = serializer.validated_data.get("id")
file = serializer.validated_data.pop('file')
file_path = f'/tmp/{file.name}'
with open(file_path, 'wb+') as temp_file:
for chunk in file.chunks():
temp_file.write(chunk)
save_file_in_background.delay(id, file_path)
return Response(serializer.data, status=status.HTTP_201_CREATED)
2 - 更新 Celery 任务:
@shared_task
def save_file_in_background(id, file_path):
try:
archive = Archive.objects.get(pk=id)
with open(file_path, 'rb') as file:
archive.file.save(file_path.split('/')[-1], ContentFile(file.read()))
archive.save()
except Archive.DoesNotExist:
pass