annotate gpp/accounts/management/commands/rate_limit_clear.py @ 506:09a9402e4a71

Added the rate_limit_clear management command, to delete IP addresses from the rate limit datastore.
author Brian Neal <bgneal@gmail.com>
date Sat, 03 Dec 2011 20:46:41 +0000
parents
children 6f5fff924877
rev   line source
bgneal@506 1 """
bgneal@506 2 The rate_limit_clear command is used to clear IP addresses out from our rate
bgneal@506 3 limit protection database.
bgneal@506 4
bgneal@506 5 """
bgneal@506 6 from optparse import make_option
bgneal@506 7 import re
bgneal@506 8
bgneal@506 9 from django.core.management.base import BaseCommand
bgneal@506 10 import redis
bgneal@506 11
bgneal@506 12 IP_RE = re.compile(r'^\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}$')
bgneal@506 13
bgneal@506 14
bgneal@506 15 class Command(BaseCommand):
bgneal@506 16 help = """Remove IP addresses from the rate limit protection datastore."""
bgneal@506 17 option_list = list(BaseCommand.option_list) + [
bgneal@506 18 make_option("--purge", action="store_true",
bgneal@506 19 help="Purge all IP addresses"),
bgneal@506 20 ]
bgneal@506 21
bgneal@506 22 def handle(self, *args, **kwargs):
bgneal@506 23 try:
bgneal@506 24 con = redis.Redis()
bgneal@506 25
bgneal@506 26 # get all rate-limit keys
bgneal@506 27 keys = con.keys('rate-limit-*')
bgneal@506 28
bgneal@506 29 # if purging, delete them all...
bgneal@506 30 if kwargs['purge']:
bgneal@506 31 if keys:
bgneal@506 32 con.delete(*keys)
bgneal@506 33 return
bgneal@506 34
bgneal@506 35 # otherwise delete the ones the user asked for
bgneal@506 36 ips = []
bgneal@506 37 for ip in args:
bgneal@506 38 if IP_RE.match(ip):
bgneal@506 39 key = 'rate-limit-%s' % ip
bgneal@506 40 if key in keys:
bgneal@506 41 ips.append(key)
bgneal@506 42 else:
bgneal@506 43 self.stdout.write('%s not found\n' % ip)
bgneal@506 44 else:
bgneal@506 45 self.stderr.write('invalid IP address %s\n' % ip)
bgneal@506 46
bgneal@506 47 if ips:
bgneal@506 48 con.delete(*ips)
bgneal@506 49
bgneal@506 50 except redis.RedisError, e:
bgneal@506 51 self.stderr.write('%s\n' % e)