##// END OF EJS Templates
Removed unused imports
neko259 -
r1949:af29e740 default
parent child Browse files
Show More
@@ -1,145 +1,143 b''
1 1 """
2 2 This module contains helper functions and helper classes.
3 3 """
4 4 import time
5 5 import uuid
6 6
7 7 import hashlib
8 import hmac
9 8 import magic
10 9 import os
11 10 from django import forms
12 11 from django.core.cache import cache
13 12 from django.db.models import Model
14 13 from django.template.defaultfilters import filesizeformat
15 14 from django.utils import timezone
16 15 from django.utils.translation import ugettext_lazy as _
17 16
18 17 import boards
19 18 from boards.abstracts.constants import FILE_DIRECTORY
20 19 from boards.settings import get_bool
21 from neboard import settings
22 20
23 21 CACHE_KEY_DELIMITER = '_'
24 22
25 23 HTTP_FORWARDED = 'HTTP_X_FORWARDED_FOR'
26 24 META_REMOTE_ADDR = 'REMOTE_ADDR'
27 25
28 26 SETTING_MESSAGES = 'Messages'
29 27 SETTING_ANON_MODE = 'AnonymousMode'
30 28
31 29 ANON_IP = '127.0.0.1'
32 30
33 31 FILE_EXTENSION_DELIMITER = '.'
34 32
35 33
36 34 def is_anonymous_mode():
37 35 return get_bool(SETTING_MESSAGES, SETTING_ANON_MODE)
38 36
39 37
40 38 def get_client_ip(request):
41 39 if is_anonymous_mode():
42 40 ip = ANON_IP
43 41 else:
44 42 x_forwarded_for = request.META.get(HTTP_FORWARDED)
45 43 if x_forwarded_for:
46 44 ip = x_forwarded_for.split(',')[-1].strip()
47 45 else:
48 46 ip = request.META.get(META_REMOTE_ADDR)
49 47 return ip
50 48
51 49
52 50 # TODO The output format is not epoch because it includes microseconds
53 51 def datetime_to_epoch(datetime):
54 52 return int(time.mktime(timezone.localtime(
55 53 datetime,timezone.get_current_timezone()).timetuple())
56 54 * 1000000 + datetime.microsecond)
57 55
58 56
59 57 # TODO Test this carefully
60 58 def cached_result(key_method=None):
61 59 """
62 60 Caches method result in the Django's cache system, persisted by object name,
63 61 object name, model id if object is a Django model, args and kwargs if any.
64 62 """
65 63 def _cached_result(function):
66 64 def inner_func(obj, *args, **kwargs):
67 65 cache_key_params = [obj.__class__.__name__, function.__name__]
68 66
69 67 cache_key_params += args
70 68 for key, value in kwargs:
71 69 cache_key_params.append(key + ':' + value)
72 70
73 71 if isinstance(obj, Model):
74 72 cache_key_params.append(str(obj.id))
75 73
76 74 if key_method is not None:
77 75 cache_key_params += [str(arg) for arg in key_method(obj)]
78 76
79 77 cache_key = CACHE_KEY_DELIMITER.join(cache_key_params)
80 78
81 79 persisted_result = cache.get(cache_key)
82 80 if persisted_result is not None:
83 81 result = persisted_result
84 82 else:
85 83 result = function(obj, *args, **kwargs)
86 84 if result is not None:
87 85 cache.set(cache_key, result)
88 86
89 87 return result
90 88
91 89 return inner_func
92 90 return _cached_result
93 91
94 92
95 93 def get_file_hash(file) -> str:
96 94 md5 = hashlib.md5()
97 95 for chunk in file.chunks():
98 96 md5.update(chunk)
99 97 return md5.hexdigest()
100 98
101 99
102 100 def validate_file_size(size: int):
103 101 max_size = boards.settings.get_int('Forms', 'MaxFileSize')
104 102 if 0 < max_size < size:
105 103 raise forms.ValidationError(
106 104 _('File must be less than %s but is %s.')
107 105 % (filesizeformat(max_size), filesizeformat(size)))
108 106
109 107
110 108 def get_extension(filename):
111 109 return filename.split(FILE_EXTENSION_DELIMITER)[-1:][0]
112 110
113 111
114 112 def get_upload_filename(model_instance, old_filename):
115 113 extension = get_extension(old_filename)
116 114 new_name = '{}.{}'.format(uuid.uuid4(), extension)
117 115
118 116 return os.path.join(FILE_DIRECTORY, new_name)
119 117
120 118
121 119 def get_file_mimetype(file) -> str:
122 120 buf = b''
123 121 for chunk in file.chunks():
124 122 buf += chunk
125 123
126 124 file_type = magic.from_buffer(buf, mime=True)
127 125 if file_type is None:
128 126 file_type = 'application/octet-stream'
129 127 elif type(file_type) == bytes:
130 128 file_type = file_type.decode()
131 129 return file_type
132 130
133 131
134 132 def get_domain(url: str) -> str:
135 133 """
136 134 Gets domain from an URL with random number of domain levels.
137 135 """
138 136 domain_parts = url.split('/')
139 137 if len(domain_parts) >= 2:
140 138 full_domain = domain_parts[2]
141 139 else:
142 140 full_domain = ''
143 141
144 142 return full_domain
145 143
General Comments 0
You need to be logged in to leave comments. Login now