Padoga
Padoga

Reputation: 535

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

Problem for upload_subscribers.delay parameters can only be integers or strings, I would not be able to pass request or your_file as a parameter into the function. How can I fix the below code so it can be run as a background task in 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

Upvotes: 0

Views: 721

Answers (1)

sonus21
sonus21

Reputation: 5388

There're two ways to solve this problem,

  • Send entire data of the file as function argument
  • Save the file in some storage system like Disk, S3, Database, etc, send this file location to the celery task.
data = ""
with open(your_file, "rb") as f:
    data = f.read()
upload_subscribers.delay( data )

Upvotes: 1

Related Questions