def handle(self, *args, **options):
        if not args or (args and args[0] not in ('load', 'update')):
            raise CommandError("USAGE: ./manage.py %s load" % \
                    os.path.basename(__file__).split('.')[0])

        transaction.enter_transaction_management()
        transaction.managed(True)

        year = CONSTITUENCY_YEAR.strftime("%Y")
        
        constituencies = twfy.getConstituencies(date=year)
        if args[0] == 'load':
            for c in constituencies:
                try:
                    lat, lon = (c['centre_lat'], c['centre_lon'])
                except KeyError:
                    # this happens for Northern Ireland - no geodata available
                    lat, lon = (None, None)

                # XXX new "api" inconsistuency
                name = c.get('name', c.get('Name', '')) 
                item = models.Constituency(name=name,
                                           year=CONSTITUENCY_YEAR,
                                           lat=lat,
                                           lon=lon)
                item.slug = smart_slugify(item.name, 
                                          manager=models.Constituency.objects,
                                          lower_case=True)

                if not ("silent" in options) or options["silent"] == False:
                    print "Loading %s <%s>" % (item.name, item.slug)

                item.save()
        else:
            geometries = twfy.getGeometry()
            for c in constituencies:
                name = c.get('name', c.get('Name', ''))
                item = models.Constituency.objects.\
                       filter(name=name,
                              year=CONSTITUENCY_YEAR).get()
                c.update(geometries[name])
                try:
                    item.lat = c['centre_lat']
                    item.lon = c['centre_lon']
                except KeyError:
                    # this happens for Northern Ireland
                    continue
                #if not ("silent" in options) or options["silent"] == False:
                #    print "Updating %s (%d, %d)" % \
                #          (item.name, item.lat, item.lon)
                item.save()
            for user in models.CustomUser.objects.all():
                constituency_name = twfy.getConstituency(user.postcode)
                try:
                    constituency = models.Constituency.objects.all()\
                                   .filter(name=constituency_name)\
                                   .filter(year=CONSTITUENCY_YEAR).get()
                except models.Constituency.DoesNotExist:
                    print "error:", user
                    continue
                user.constituencies.add(constituency)
                user.save()
                prior = user.constituencies.filter(year__lt=CONSTITUENCY_YEAR)
                prior = prior.order_by('signup_customuser_constituencies.id')
                if len(prior) > 1:
                    print user, "has extra constituencies"
                for extra in prior[1:]:

                    constituency_set = models.Constituency.objects\
                                       .filter(year=CONSTITUENCY_YEAR)
                    distances = []
                    for c in constituency_set:
                        if not c.lat or not extra.lat:
                            continue
                        distance = geo.haversine((c.lat, c.lon),
                                                 (extra.lat, extra.lon))

                        distances.append((c, distance))
                    nearest = sorted(distances, key=lambda x: x[1])
                    if nearest:
                        constituency = nearest[0][0]
                        print " old", extra, "new", constituency
                        user.constituencies.add(constituency)
                        user.save()
                    else:
                        print " couldn't work out new additionals for",user, extra
                #if not ("silent" in options) or options["silent"] == False:
                #    print "reset home constituency for %s" % user

                
        transaction.commit()
Ejemplo n.º 2
0
    def handle(self, *args, **options):
        """
            The 'touch' command fires the user_touch signal on every
            user on the site. This allows tasks to :
            assign themselves
            to pre-existing users (in addition to new users, as handled
            by user_signup)
            """
        if not args:
            raise CommandError("Please specify a command, e.g. 'touch' or 'email'")
        if args[0] not in ('touch','email'):
            raise CommandError("Unknown command '%s'" % args[0])
        near_postcode = options.get('near_postcode', None)
        if not near_postcode:
            has_distance = options['max_distance']
            has_number = options['max_number']
            
            if has_distance and not has_number:
                raise CommandError("'--max-distance' option requires a "
                                   "postcode")
            if has_number and (not has_distance and not options['random']):
                raise CommandError("'--max-number' option requires a "
                                   "postcode or --random flag")
            
        if hasattr(options, 'max_distance') and not near_postcode:
            raise CommandError("'max-distance' option requires a postcode")
        max_distance = options['max_distance'] \
                       and int(options['max_distance']) or None
        max_number = options['max_number'] \
                     and int(options['max_number']) or None
        if near_postcode:
            constituencies = []
            constituency_name = twfy.getConstituency(near_postcode)
            constituency = Constituency.objects.all()\
                           .filter(name=constituency_name)\
                           .get(year=settings.CONSTITUENCY_YEAR)
            neighbours = constituency.neighbors(limit=max_number,
                                                within_km=max_distance)
            users = ConstituencyUserChain(constituency, neighbours)

        else:
            users = CustomUser.objects.all()
        if options['random']:
            users = users.order_by('?')
        queryfilter = options.get('queryfilter', '')
        if queryfilter:
            users = eval(queryfilter)
        emailfilter = options.get('emailfilter', '')
        if emailfilter:
            users = users.filter(email__icontains=emailfilter)
        task_slug = options.get('task_slug', None)
        dry_run = options.get('dry_run', False)

        count = 0
        for user in users:
            if max_number and count == max_number:
                break
            msg = "user %s" % user
            if args[0] == "touch":
                msg += "\n  touching:"
                responses = []
                if task_slug:
                    if dry_run:
                        print task_slug
                        count += 1
                    else:
                        if TaskUser.objects.filter(user=user,
                                                   task__slug=task_slug):
                            continue
                        else:
                            responses = user_touch.send(self,
                                                        user=user,
                                                        task_slug=task_slug)
                            count += 1
                else:
                    for task in Task.objects.all():
                        if dry_run:
                            print task.slug
                            count += 1
                        else:
                            if TaskUser.objects.filter(user=user,
                                                       task__slug=task_slug):
                                continue                            
                            result = user_touch.send(self,
                                                     user=user,
                                                     task_slug=task.slug)
                            responses.extend(result)
                            count += 1
                    msg += "\n  ".join([x[1] for x in responses\
                                        if x[1]])
            elif args[0] == "email":
                emailed_on_this_round = []
                for task in TaskUser.objects.filter(user=user):
                    if task_slug and task_slug != task.task.slug:
                        continue
                    if user.email not in emailed_on_this_round:
                        sent = False
                        if not dry_run:
                            try:
                                sent = task.send_email(force=True)
                            except RegistrationProfile.DoesNotExist:
                                msg + "\n  no profile found for %s" % user.email
                        if sent:
                            msg += "\n  emailing about %s" % task.task.slug
                        else:
                            msg += "\n  no emails assigned for %s" % task.task.slug
                        emailed_on_this_round.append(user.email)
                    else:
                        msg += "\n   already emailed today"
                    
            print msg