Mercurial > public > sg101
comparison gpp/potd/management/commands/pick_potd.py @ 515:ae89ba801e8b
For #194, convert the POTD management command to a celery task.
Refactored to put the logic for the command into a function, and the command simply calls this function. The task can also just call this function. Added some basic tests for the new function.
author | Brian Neal <bgneal@gmail.com> |
---|---|
date | Wed, 14 Dec 2011 02:41:15 +0000 |
parents | dbd703f7d63a |
children |
comparison
equal
deleted
inserted
replaced
514:6d816aa586c1 | 515:ae89ba801e8b |
---|---|
1 """ | 1 """ |
2 pick_potd is a custom manage.py command for the POTD application. | 2 pick_potd is a custom manage.py command for the POTD application. |
3 It is intended to be called from a cron job at midnight to pick the | 3 Calling it will pick a new POTD. |
4 new POTD. | 4 |
5 """ | 5 """ |
6 | |
7 import random | |
8 from django.core.management.base import NoArgsCommand | 6 from django.core.management.base import NoArgsCommand |
9 | 7 |
10 from potd.models import Current | 8 from potd.tools import pick_potd |
11 from potd.models import Sequence | |
12 from potd.models import Photo | |
13 | 9 |
14 def get_sequence(): | |
15 try: | |
16 s = Sequence.objects.get(pk=1) | |
17 if s.seq: | |
18 return [int(x) for x in s.seq.split(',')] | |
19 except: | |
20 pass | |
21 return [] | |
22 | |
23 def new_sequence(): | |
24 the_ids = Photo.objects.values_list('id', flat=True).order_by('id') | |
25 ids = [] | |
26 for id in the_ids.iterator(): | |
27 ids.append(int(id)) | |
28 | |
29 random.shuffle(ids) | |
30 try: | |
31 s = Sequence.objects.get(pk=1) | |
32 except Sequence.DoesNotExist: | |
33 s = Sequence() | |
34 | |
35 s.seq = ','.join([str(id) for id in ids]) | |
36 s.save() | |
37 return ids | |
38 | 10 |
39 class Command(NoArgsCommand): | 11 class Command(NoArgsCommand): |
40 help = "Chooses the next POTD. Run this command at midnight to update the POTD." | 12 help = "Chooses the next POTD." |
41 #requires_model_validation = False | |
42 | 13 |
43 def handle_noargs(self, **options): | 14 def handle_noargs(self, **options): |
44 try: | 15 pick_potd() |
45 c = Current.objects.get(pk=1) | |
46 current = c.potd.pk | |
47 except Current.DoesNotExist: | |
48 c = Current() | |
49 current = None | |
50 | |
51 seq = get_sequence() | |
52 if current is None or len(seq) == 0 or current == seq[-1]: | |
53 # time to generate a new random sequence | |
54 seq = new_sequence() | |
55 # set current to the first one in the sequence | |
56 if len(seq) > 0: | |
57 try: | |
58 c.potd = Photo.objects.get(pk=seq[0]) | |
59 c.potd.potd_count += 1 | |
60 c.potd.save() | |
61 c.save() | |
62 except: | |
63 pass | |
64 else: | |
65 # find current in the sequence, pick the next one | |
66 try: | |
67 i = seq.index(current) | |
68 c.potd = Photo.objects.get(pk=seq[i + 1]) | |
69 c.potd.potd_count += 1 | |
70 c.potd.save() | |
71 c.save() | |
72 except: | |
73 pass | |
74 |