annotate 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
rev   line source
gremmie@1 1 """
gremmie@1 2 pick_potd is a custom manage.py command for the POTD application.
gremmie@1 3 It is intended to be called from a cron job at midnight to pick the
gremmie@1 4 new POTD.
gremmie@1 5 """
gremmie@1 6
gremmie@1 7 import random
gremmie@1 8 from django.core.management.base import NoArgsCommand
gremmie@1 9
gremmie@1 10 from potd.models import Current
gremmie@1 11 from potd.models import Sequence
gremmie@1 12 from potd.models import Photo
gremmie@1 13
gremmie@1 14 def get_sequence():
gremmie@1 15 try:
gremmie@1 16 s = Sequence.objects.get(pk=1)
gremmie@1 17 if s.seq:
gremmie@1 18 return [int(x) for x in s.seq.split(',')]
gremmie@1 19 except:
gremmie@1 20 pass
gremmie@1 21 return []
gremmie@1 22
gremmie@1 23 def new_sequence():
gremmie@1 24 the_ids = Photo.objects.values_list('id', flat=True).order_by('id')
gremmie@1 25 ids = []
gremmie@1 26 for id in the_ids.iterator():
gremmie@1 27 ids.append(int(id))
gremmie@1 28
gremmie@1 29 random.shuffle(ids)
gremmie@1 30 try:
gremmie@1 31 s = Sequence.objects.get(pk=1)
gremmie@1 32 except Sequence.DoesNotExist:
gremmie@1 33 s = Sequence()
gremmie@1 34
gremmie@1 35 s.seq = ','.join([str(id) for id in ids])
gremmie@1 36 s.save()
gremmie@1 37 return ids
gremmie@1 38
gremmie@1 39 class Command(NoArgsCommand):
gremmie@1 40 help = "Chooses the next POTD. Run this command at midnight to update the POTD."
gremmie@1 41 #requires_model_validation = False
gremmie@1 42
gremmie@1 43 def handle_noargs(self, **options):
gremmie@1 44 try:
gremmie@1 45 c = Current.objects.get(pk=1)
gremmie@1 46 current = c.potd.pk
gremmie@1 47 except Current.DoesNotExist:
gremmie@1 48 c = Current()
gremmie@1 49 current = None
gremmie@1 50
gremmie@1 51 seq = get_sequence()
gremmie@1 52 if current is None or len(seq) == 0 or current == seq[-1]:
gremmie@1 53 # time to generate a new random sequence
gremmie@1 54 seq = new_sequence()
gremmie@1 55 # set current to the first one in the sequence
gremmie@1 56 if len(seq) > 0:
gremmie@1 57 try:
gremmie@1 58 c.potd = Photo.objects.get(pk=seq[0])
gremmie@1 59 c.potd.potd_count += 1
gremmie@1 60 c.potd.save()
gremmie@1 61 c.save()
gremmie@1 62 except:
gremmie@1 63 pass
gremmie@1 64 else:
gremmie@1 65 # find current in the sequence, pick the next one
gremmie@1 66 try:
gremmie@1 67 i = seq.index(current)
gremmie@1 68 c.potd = Photo.objects.get(pk=seq[i + 1])
gremmie@1 69 c.potd.potd_count += 1
gremmie@1 70 c.potd.save()
gremmie@1 71 c.save()
gremmie@1 72 except:
gremmie@1 73 pass
gremmie@1 74