1 from os.path import join, isfile
2 from django.core.urlresolvers import reverse
3 from django.db import models
4 from djcelery.models import TaskMeta
5 from waiter.settings import WAITER_URL
6 from waiter.utils import check_abspath
7 from picklefield import PickledObjectField
10 class WaitedFile(models.Model):
11 path = models.CharField(max_length=255, unique=True, db_index=True)
12 task = PickledObjectField(null=True, editable=False)
13 description = models.CharField(max_length=255, null=True, blank=True)
16 def exists(cls, path):
17 """Returns opened file or None.
19 `path` is relative to WAITER_ROOT.
20 Won't open a path leading outside of WAITER_ROOT.
22 abs_path = check_abspath(path)
23 # Pre-fetch objects for deletion to avoid minor race condition
24 relevant = [o.id for o in cls.objects.filter(path=path)]
26 cls.objects.filter(id__in=relevant).delete()
33 # Race; just let the other task roll.
35 if self.task.status not in (u'PENDING', u'STARTED', u'SUCCESS', u'RETRY'):
40 def order(cls, path, task_creator, description=None):
42 Returns an URL for the user to follow.
43 If the file is ready, returns download URL.
44 If not, starts preparing it and returns waiting URL.
46 task_creator: function taking a path and generating the file;
47 description: a string or string proxy with a description for user;
49 already = cls.exists(path)
51 waited, created = cls.objects.get_or_create(path=path)
52 if created or waited.is_stale():
53 waited.task = task_creator(check_abspath(path))
54 waited.description = description
56 return reverse("waiter", args=[path])
57 return join(WAITER_URL, path)