Created
August 30, 2014 03:39
-
-
Save shonenada/c334e8d5703800023040 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class RequestLimit: | |
def addRequest(self, ipp_addr, bcookie): | |
blkip = memcache.get('RequestLimitList') | |
if blkip is None: | |
blkip = [{ | |
'ip_addr': ip_addr, | |
'bcookie': bcookie, | |
'count': 1, | |
'base_time': datetime.datetime.now(), | |
'update_time': date.datetime.now(), | |
'status': 'ok' | |
},] | |
memcache.add('RequestLimitList', blkip) | |
else: | |
ip_exists = False | |
for ips in blkip: | |
if ips['ip_addr'] == ip_addr: | |
ip_exists = True | |
if (not bcookie) or ips.has_key('bcookie') and ips['bcookie'] == bcookie: | |
ips['count'] += 1 | |
ips['update_time'] = datetime.datetime.now() | |
period = ips['update_time'] - ips['base_time'] | |
if period.seconds > 30 and ips['status'] == 'ok': | |
ips['base_time'] = ips['update_time'] | |
ips['count'] = 1 | |
break | |
else: | |
pass | |
if ip_exists == False: | |
blkip.append({ | |
'ip_addr': ip_addr, | |
'bcookie': bcookie, | |
'count': 1, | |
'base_time': datetime.datetime.now(), | |
'update_time': datetime.datetime.now(), | |
'status': 'ok'}) | |
memcache.set('RequestLimitList', blkip) | |
return | |
def checkIPInBlackList(self, ip_addr, bcookie): | |
blkip = memcache.get('RequestLimitList') | |
found = False | |
for ips in blkip: | |
if (ips['ip_addr'] == ip_addr): | |
reqs_time = datetime.datetime.now() - ips['base_time'] | |
if (ips['status'] == 'banned'): | |
if (reqs_time.seconds >= PLANETCONFIG['REQUESTLIMITFREETIME']): | |
ips['count'] = 1 | |
ips['base_time'] = datetime.datetime.now() | |
ips['update_time'] = datetime.datetime.now() | |
ips['status'] = 'ok' | |
memcache.set('RequestLimitList', blkip) | |
else: | |
found = True | |
break | |
if ips['count'] >= PLANETCONFIG['REQUESTLIMITPERHALFMIN']: | |
if (reqs_time.seconds < 30): | |
found = True | |
ips['count'] = 1 | |
ips['base_time'] = datetime.datetime.now() | |
ips['update_time'] = datetime.datetime.now() | |
ips['status'] = 'banned' | |
memcache.set('RequestLimitList', blkip) | |
break | |
return found | |
reqlimit = RequestLimit() | |
reqlimit.addRequestClick(ip, bcookie) | |
if (reqlimit.checkIPInBlackList(ip, bcookie) == True): | |
self.response.set_status(444, 'request too busy') | |
self.renderTemplate('common/requestlimit.hmtl') | |
return False |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment