PaferaPy Async 0.1
ASGI framework focused on simplicity and efficiency
Loading...
Searching...
No Matches
utils.py
Go to the documentation of this file.
1#!/usr/bin/python
2# -*- coding: utf-8 -*-
3
4import random
5import importlib
6import base64
7
8# =====================================================================
9def MakeRID():
10 """Returns a random 32-bit int ID.
11 """
12 return random.randint(-2147483648, 2147483647)
13
14# =====================================================================
16 """Returns a random 64-bit int ID.
17 """
18 return random.randint(-9223372036854775808, 9223372036854775807)
19
20# =====================================================================
21def Bound(val, min, max):
22 """Returns a value that is no smaller than min or larger than max.
23 """
24 if val < min:
25 val = min
26
27 if val > max:
28 val = max
29
30 return val
31
32# =====================================================================
34 val,
35 chars = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ-_'
36):
37 """Turns a 32-bit value into a six character alphanumeric code. Useful
38 for shortening JSON data or use in URLs.
39
40 Thanks to http://programanddesign.com/php/base62-encode/
41 """
42 val = int(val) + 2147483648
43
44 base = len(chars)
45 code = ''
46
47 while True:
48 mod = int(val % base)
49 code = chars[mod] + code
50 val = (val - mod) / base
51
52 if val <= 0:
53 break
54
55 while len(code) < 6:
56 code = '0' + code
57
58 return code
59
60# =====================================================================
62 code,
63 chars = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ-_'
64):
65 """Turns a six character alphanumeric code into a 32-bit value. It's
66 the reverse of ToShortCode()
67 """
68 base = len(chars)
69
70 l = len(code)
71 val = 0;
72
73 chars = [c for c in chars]
74 arr = {}
75
76 for i in range(0, base):
77 arr[chars[i]] = i
78
79 for i in range(0, l):
80 val = val + (arr[code[i]] * (base ** (l - i - 1)))
81
82 val = val - 2147483648
83
84 return val
85
86# =====================================================================
87def CodeDir(code):
88 """Separates a filename into three character segments with the
89 directory separator '/' in between. Useful for avoiding having
90 millions of small files inside of the same directory, which is known
91 to severely degrade performance on some filesystems.
92 """
93 ls = []
94 i = 0
95 l = len(code)
96
97 while i < l:
98 ls.append(code[i:i + 3])
99 i += 3
100
101 return '/'.join(ls)
102
103# =====================================================================
104def BestTranslation(translations, languages, defaultlang = 'en'):
105 """Returns the best translation found in a dict of different
106 translations.
107
108 languages should be a list of of ISO 639-1 language codes.
109
110 defaultlang is set to 'en', so be sure to set it to your native
111 language if used on other systems.
112 """
113 if not translations:
114 return '--'
115
116 if not isinstance(languages, list):
117 languages = [languages]
118
119 for l in languages:
120 if l in translations and translations[l]:
121 return translations[l]
122
123 if defaultlang in translations:
124 return translations[defaultlang]
125
126 return translations[list(translations.keys())[0]]
127
128# =====================================================================
129def LoadTranslation(g, app, translation, languages):
130 """Load the translation into the global language dict in g.T
131
132 languages should be a list of of ISO 639-1 language codes.
133
134 'en' will always be the last language code on the list.
135 """
136 T = g.T
137
138 if not isinstance(languages, list):
139 languages = [languages]
140
141 languages.append('en')
142
143 for lang in languages:
144 try:
145 with open('static/' + app + '/translations/' + lang + '/' + translation + '.js', 'r') as f:
146 exec(f.read())
147
148 return lang
149 except Exception as e:
150 pass
151
152 raise Exception(f"Translation {app}/{translation} was not found for {languages}")
153
154# =====================================================================
155def GetModel(model):
156 """Returns the model object from the correct module.
157 """
158 if not model:
159 raise Exception('GetModel: Missing model name')
160
161 parts = model.split('_')
162
163 if len(parts) != 2:
164 raise Exception(f"GetModel: {model} doesn't look like a valid model name.")
165
166 module = importlib.import_module('apps.' + parts[0])
167
168 if model not in dir(module):
169 raise Exception(f"GetModel: Model {model} not found in module apps.{parts[0]}")
170
171 return getattr(module, model)
172
173# =====================================================================
175 """Helper function to ensure that a b64 string is correctly padded to
176 four spaces.
177 """
178
179 #if not isinstance(s, bytes):
180 # s = s.encode('utf-8')
181
182 missing_padding = len(s) % 4
183
184 if missing_padding:
185 s += '=' * (4 - missing_padding)
186
187 return base64.b64decode(s)
188
189# =====================================================================
191 """Escapes special characters to be used in a SQL query string.
192
193 Taken from mysql-connector's version.
194 """
195 ls = [];
196
197 for c in s:
198 if c == '\\n':
199 ls.append('\\\\n')
200 elif c == '\\r':
201 ls.append('\\\\r')
202 elif c == '\\':
203 ls.append('\\\\')
204 elif c == "'":
205 ls.append("\\'")
206 elif c == '"':
207 ls.append('\\"')
208 elif c == '\u00a5' or c == '\u20a9':
209 #escape characters interpreted as backslash by mysql
210 #fall through
211 pass
212 else:
213 ls.append(c)
214
215 return ''.join(ls)
216
217# =====================================================================
218def KeyFromValue(ls, value):
219 """Does a reverse lookup to find the key of a value in a dict.
220 """
221 return ls.keys()[ls.values().index(value)]
def KeyFromValue(ls, value)
Does a reverse lookup to find the key of a value in a dict.
Definition: utils.py:218
def EscapeSQL(s)
Escapes special characters to be used in a SQL query string.
Definition: utils.py:190
def Bound(val, min, max)
Returns a value that is no smaller than min or larger than max.
Definition: utils.py:21
def FromShortCode(code, chars='0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ-_')
Turns a six character alphanumeric code into a 32-bit value.
Definition: utils.py:64
def GetModel(model)
Returns the model object from the correct module.
Definition: utils.py:155
def ToShortCode(val, chars='0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ-_')
Turns a 32-bit value into a six character alphanumeric code.
Definition: utils.py:36
def MakeRID()
Returns a random 32-bit int ID.
Definition: utils.py:9
def BestTranslation(translations, languages, defaultlang='en')
Returns the best translation found in a dict of different translations.
Definition: utils.py:104
def b64decodepad(s)
Helper function to ensure that a b64 string is correctly padded to four spaces.
Definition: utils.py:174
def MakeRBID()
Returns a random 64-bit int ID.
Definition: utils.py:15
def CodeDir(code)
Separates a filename into three character segments with the directory separator '/' in between.
Definition: utils.py:87
def LoadTranslation(g, app, translation, languages)
Load the translation into the global language dict in g.T.
Definition: utils.py:129