简体   繁体   English

是否可以将模型对象连接到芹菜任务?

[英]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 我有一个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 ty

EDIT 1: 编辑1:

Suppose I send in queue a task for this afternoon at 15:30 and I tell it to create a model object. 假设我在今天下午15:30排队发送任务,并告诉它创建模型对象。

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... 之后,我需要在该模型对象中编辑某些内容,任务时间不再是15:30,而是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 它在db中写了一个task_id somethign

<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. 我的目标是在某处备份task_id,并在我更改任务本身的某些内容时将其撤消。

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 您可以将任务的ID设置为任意值,并在处理任务之前使用此ID撤销任务

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()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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