【发布时间】:2021-10-21 00:08:07
【问题描述】:
我正在尝试使用带有 Celery 的 Django 和 DRF 上传和处理 excel 文件。 当我尝试将文件传递给我的 Celery 任务以在后台处理时出现问题,我收到以下错误:
kombu.exceptions.EncodeError: Object of type InMemoryUploadedFile is not JSON serializable
这是我的视图发布请求处理程序:
class FileUploadView(generics.CreateAPIView):
"""
POST: upload file to save data in the database
"""
parser_classes = [MultiPartParser]
serializer_class = FileSerializerXLSX
def post(self, request, format=None):
"""
Allows to upload file and lets it be handled by pandas
"""
serialized = FileSerializerXLSX(data=request.data)
if serialized.is_valid():
file_obj = request.data['file']
# file_bytes = file_obj.read()
print(file_obj)
import_excel_task.delay(file_obj)
print("its working")
return Response(status=204)
return Response(serialized._errors, status=status.HTTP_400_BAD_REQUEST)
还有我的芹菜任务:
def import_excel_helper(file_obj):
df = extract_excel_to_dataframe(file_obj)
transform_df_to_clientmodel(df)
transform_df_to_productmodel(df)
transform_df_to_salesmodel(df)
@shared_task(name="import_excel_task")
def import_excel_task(file_obj):
"""Save excel file in the background"""
logger.info("Importing excel file")
import_excel_helper(file_obj)
知道如何处理将 Excel 文件导入 celery 任务以便后台其他函数处理它吗?
【问题讨论】:
-
设置
CELERY_TASK_SERIALIZER(和CELERY_ACCEPT_CONTENT)可能有助于解决这个问题。 -
@JPG 该文件是 excel 文件,因此在将其加载到数据框之前,我不知道如何将其转换为 json。
标签: django django-rest-framework celery