上传一个 Excel 文件作为 celery 的后台任务? - 芹菜 Redis Python Django

Upload an Excel file as a background task in celery? - Celery Redis Python Django

问题 for upload_subscribers.delay 参数只能是整数或字符串,我将无法传递 requestyour_file 作为函数中的参数。我怎样才能修复下面的代码,以便它可以 运行 作为 celery 中的后台任务?

import pandas as pd
from .models import Subscriber

def upload_subscribers(request):
    template = "audiences/upload.html"
    if request.method == "POST":
        your_file = request.FILES['file']

        if your_file.name.endswith('.xlsx'):
            df = pd.read_excel(your_file)

            for index, row in df.iterrows():
                created = Subscriber.objects.update_or_create(
                    email= row[2],
                    defaults = {
                        "first_name": row[0],
                        "last_name": row[1],
                    })

    return None

有两种方法可以解决这个问题,

  • 将文件的全部数据作为函数参数发送
  • 将文件保存在一些存储系统中,如磁盘、S3、数据库等,将此文件位置发送到 celery 任务。
data = ""
with open(your_file, "rb") as f:
    data = f.read()
upload_subscribers.delay( data )