utils.py
69 lines
| 1.9 KiB
| text/x-python
|
PythonLexer
/ boards / utils.py
Ilyas
|
r78 | """ | ||
This module contains helper functions and helper classes. | ||||
""" | ||||
neko259
|
r716 | import time | ||
neko259
|
r853 | import hmac | ||
neko259
|
r957 | from django.core.cache import cache | ||
from django.db.models import Model | ||||
neko259
|
r716 | |||
neko259
|
r542 | from django.utils import timezone | ||
wnc_21
|
r95 | |||
neko259
|
r81 | from neboard import settings | ||
Ilyas
|
r78 | |||
wnc_21
|
r95 | KEY_CAPTCHA_FAILS = 'key_captcha_fails' | ||
KEY_CAPTCHA_DELAY_TIME = 'key_captcha_delay_time' | ||||
KEY_CAPTCHA_LAST_ACTIVITY = 'key_captcha_last_activity' | ||||
neko259
|
r210 | def get_client_ip(request): | ||
x_forwarded_for = request.META.get('HTTP_X_FORWARDED_FOR') | ||||
if x_forwarded_for: | ||||
ip = x_forwarded_for.split(',')[-1].strip() | ||||
else: | ||||
ip = request.META.get('REMOTE_ADDR') | ||||
neko259
|
r542 | return ip | ||
neko259
|
r990 | # TODO The output format is not epoch because it includes microseconds | ||
neko259
|
r542 | def datetime_to_epoch(datetime): | ||
return int(time.mktime(timezone.localtime( | ||||
datetime,timezone.get_current_timezone()).timetuple()) | ||||
neko259
|
r765 | * 1000000 + datetime.microsecond) | ||
neko259
|
r853 | |||
def get_websocket_token(user_id='', timestamp=''): | ||||
""" | ||||
Create token to validate information provided by new connection. | ||||
""" | ||||
sign = hmac.new(settings.CENTRIFUGE_PROJECT_SECRET.encode()) | ||||
sign.update(settings.CENTRIFUGE_PROJECT_ID.encode()) | ||||
sign.update(user_id.encode()) | ||||
sign.update(timestamp.encode()) | ||||
token = sign.hexdigest() | ||||
neko259
|
r957 | return token | ||
def cached_result(function): | ||||
""" | ||||
Caches method result in the Django's cache system, persisted by object name, | ||||
object name and model id if object is a Django model. | ||||
""" | ||||
def inner_func(obj, *args, **kwargs): | ||||
# TODO Include method arguments to the cache key | ||||
cache_key = obj.__class__.__name__ + '_' + function.__name__ | ||||
if isinstance(obj, Model): | ||||
cache_key += '_' + str(obj.id) | ||||
persisted_result = cache.get(cache_key) | ||||
if persisted_result: | ||||
result = persisted_result | ||||
else: | ||||
result = function(obj, *args, **kwargs) | ||||
cache.set(cache_key, result) | ||||
return result | ||||
neko259
|
r990 | return inner_func | ||