简体   繁体   中英

Is it possible to connect a model object to a celery task?

I need to connect a celery task to a model objects. For example, I need to create an object of a model

class AuthorPrice(models.Model):
    author = models.Charfield(default=0)
    price = models.FloatField(default=0)

I have a task.py

app = Celery()

@app.task
def create():
    new = AuthorPrice.object.create()
    new.author = John
    new.price = 30
    new.save()

I call a task in view

create.apply_async(eta.datetime(2019, 07, 31, 15, 56))

so far, everything is ok but, if i need to revoke or edit this task is possible to connect it at my model like a ForeignKey?

ty

EDIT 1:

Suppose I send in queue a task for this afternoon at 15:30 and I tell it to create a model object.

After of this i need to edit something in that model object and the time of task is no more 15:30 but 16:30...

Now my model is:

class AuthorPrice(models.Model):
    author = models.Charfield(default=0)
    price = models.FloatField(default=0)
    task = models.Charfield(default=0)

And my task is:

@app.task(bind=True)
def create(self):

    print app.AsyncResult.task_id
    new = AuthorPrice.objects.create()
    new.author = 'John'
    new.task = app.AsyncResult.task_id
    new.save()

it write in db a task_id somethign like

<property object at 0x7fc77a397b50>

but it not work if i need to revoke it...

My goal is have a backup of task_id somewhere and revoke it when i change something in the task itselfes.

Any ideas?

You can set a task's id to whatever you like and use this id to revoke the task before it's processed

import uuid
task_id = uuid.uuid4()
create.apply_async(task_id=task_id)
some_data_storage.set(key, task_id)

When you want to revoke

task_id = some_date_storage.get(key)
AsyncResult(task_id).revoke()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM