django-axes/axes/utils.py

49 lines
1.3 KiB
Python
Raw Normal View History

2016-12-07 01:01:44 +00:00
from django.core.cache import cache
from axes.models import AccessAttempt
2011-04-12 21:04:51 +00:00
2013-07-27 17:16:54 +00:00
def reset(ip=None, username=None):
"""Reset records that match ip or username, and
return the count of removed attempts.
"""
count = 0
2013-07-27 17:16:54 +00:00
attempts = AccessAttempt.objects.all()
if ip:
2013-07-27 17:16:54 +00:00
attempts = attempts.filter(ip_address=ip)
if username:
2013-07-27 17:16:54 +00:00
attempts = attempts.filter(username=username)
if attempts:
2013-07-27 17:16:54 +00:00
count = attempts.count()
2016-12-07 01:01:44 +00:00
from axes.decorators import get_cache_key
for attempt in attempts:
cache_hash_key = get_cache_key(attempt)
if cache.get(cache_hash_key):
cache.delete(cache_hash_key)
2013-07-27 17:16:54 +00:00
2016-12-07 01:01:44 +00:00
attempts.delete()
2013-07-27 17:16:54 +00:00
return count
2016-05-30 12:59:48 +00:00
2016-06-24 14:42:18 +00:00
def iso8601(timestamp):
2016-05-30 12:59:48 +00:00
"""Returns datetime.timedelta translated to ISO 8601 formatted duration.
"""
2016-06-24 14:42:18 +00:00
seconds = timestamp.total_seconds()
2016-05-30 12:59:48 +00:00
minutes, seconds = divmod(seconds, 60)
hours, minutes = divmod(minutes, 60)
days, hours = divmod(hours, 24)
date = '{:.0f}D'.format(days) if days else ''
time_values = hours, minutes, seconds
time_designators = 'H', 'M', 'S'
2016-06-24 14:42:18 +00:00
time = ''.join([
('{:.0f}'.format(value) + designator)
2016-05-30 12:59:48 +00:00
for value, designator in zip(time_values, time_designators)
if value]
)
2016-06-20 14:26:39 +00:00
return u'P' + date + (u'T' + time if time else '')