Mercurial > public > sg101
comparison gpp/potd/management/commands/pick_potd.py @ 1:dbd703f7d63a
Initial import of sg101 stuff from private repository.
author | gremmie |
---|---|
date | Mon, 06 Apr 2009 02:43:12 +0000 |
parents | |
children | ae89ba801e8b |
comparison
equal
deleted
inserted
replaced
0:900ba3c7b765 | 1:dbd703f7d63a |
---|---|
1 """ | |
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 | |
4 new POTD. | |
5 """ | |
6 | |
7 import random | |
8 from django.core.management.base import NoArgsCommand | |
9 | |
10 from potd.models import Current | |
11 from potd.models import Sequence | |
12 from potd.models import Photo | |
13 | |
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 | |
39 class Command(NoArgsCommand): | |
40 help = "Chooses the next POTD. Run this command at midnight to update the POTD." | |
41 #requires_model_validation = False | |
42 | |
43 def handle_noargs(self, **options): | |
44 try: | |
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 |