gva/gnuviechadmin/taskresults/models.py

48 lines
1.4 KiB
Python

"""
This model defines the database models to handle Celery AsyncResults.
"""
from __future__ import unicode_literals
from django.db import models
from django.utils.encoding import python_2_unicode_compatible
from django.utils.translation import ugettext as _
from gnuviechadmin.celery import app
class TaskResultManager(models.Manager):
def create_task_result(self, asyncresult, name):
taskresult = self.create(task_id=asyncresult.id, task_name=name)
return taskresult
@python_2_unicode_compatible
class TaskResult(models.Model):
task_id = models.CharField(_('Task id'), max_length=36)
task_name = models.CharField(_('Task name'), max_length=64)
result = models.TextField(_('Task result'))
finished = models.BooleanField(default=False)
state = models.CharField(_('Task state'), max_length=16)
objects = TaskResultManager()
class Meta:
verbose_name = _('Task result')
verbose_name_plural = _('Task results')
def __str__(self):
return "{task_name} ({task_id}): {finished}".format(
task_name=self.task_name,
task_id=self.task_id,
finished=_('yes') if self.finished else _('no')
)
def fetch_result(self):
if not self.finished:
ar = app.AsyncResult(self.task_id)
res = ar.get(no_ack=True, timeout=1)
self.result = str(res)
self.state = ar.state
self.finished = True