comparison potd/tools.py @ 581:ee87ea74d46b

For Django 1.4, rearranged project structure for new manage.py.
author Brian Neal <bgneal@gmail.com>
date Sat, 05 May 2012 17:10:48 -0500
parents gpp/potd/tools.py@ae89ba801e8b
children
comparison
equal deleted inserted replaced
580:c525f3e0b5d0 581:ee87ea74d46b
1 """
2 Tools for the Photo of the Day (potd) application.
3
4 """
5 import random
6 import logging
7
8 from potd.models import Current, Sequence, Photo
9
10
11 logger = logging.getLogger(__name__)
12
13
14 def get_sequence():
15 """
16 Reads the photo sequence object from the database and converts it into a
17 list of photo IDs. If the sequence object is not found, and empty list is
18 returned.
19
20 """
21 try:
22 s = Sequence.objects.get(pk=1)
23 except Sequence.DoesNotExist:
24 return []
25
26 return [int(x) for x in s.seq.split(',')]
27
28
29 def new_sequence():
30 """
31 Generates a new random sequence of photos and saves it to the database.
32 The sequence is returned as a list of photo IDs.
33
34 """
35 ids = list(Photo.objects.values_list('id', flat=True))
36 random.shuffle(ids)
37
38 try:
39 s = Sequence.objects.get(pk=1)
40 except Sequence.DoesNotExist:
41 s = Sequence()
42
43 s.seq = ','.join([str(n) for n in ids])
44 s.save()
45 return ids
46
47
48 def pick_potd():
49 """
50 Chooses the next POTD. Run this command at midnight to update the POTD.
51
52 """
53 # Get the "current" record for the now old POTD:
54 try:
55 c = Current.objects.get(pk=1)
56 current = c.potd.pk
57 except Current.DoesNotExist:
58 c = Current()
59 current = None
60
61 # Get the sequence of photo ID's:
62 seq = get_sequence()
63
64 # If there is no current object, sequence, or if this was the last POTD in
65 # the sequence, generate a new random sequence:
66
67 if current is None or not seq or current == seq[-1]:
68 # time to generate a new random sequence
69 seq = new_sequence()
70 # set current to the first one in the sequence
71 if seq:
72 try:
73 c.potd = Photo.objects.get(pk=seq[0])
74 except Photo.DoesNotExist:
75 logger.error("POTD: missing photo %d", seq[0])
76 else:
77 c.potd.potd_count += 1
78 c.potd.save()
79 c.save()
80 else:
81 # find current in the sequence, pick the next one
82 try:
83 i = seq.index(current)
84 except ValueError:
85 logger.error("POTD: current photo (%d) not in sequence", current)
86 return
87
88 n = i + 1
89 try:
90 c.potd = Photo.objects.get(pk=seq[n])
91 except Photo.DoesNotExist:
92 logger.error("POTD: missing next photo %d", n)
93 else:
94 c.potd.potd_count += 1
95 c.potd.save()
96 c.save()