forked from benadida/helios-server
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathutils.py
193 lines (148 loc) · 3.93 KB
/
utils.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
"""
Utilities.
Ben Adida - [email protected]
2005-04-11
"""
import urllib, re, sys, datetime, urlparse, string
import threading
# utils from helios_auth, too
from helios_auth.utils import *
from django.conf import settings
import random, logging
import hashlib, hmac, base64
def do_hmac(k,s):
"""
HMAC a value with a key, hex output
"""
mac = hmac.new(k, s, hashlib.sha1)
return mac.hexdigest()
def split_by_length(str, length, rejoin_with=None):
"""
split a string by a given length
"""
str_arr = []
counter = 0
while counter<len(str):
str_arr.append(str[counter:counter+length])
counter += length
if rejoin_with:
return rejoin_with.join(str_arr)
else:
return str_arr
def urlencode(str):
"""
URL encode
"""
if not str:
return ""
return urllib.quote(str)
def urlencodeall(str):
"""
URL encode everything even unresreved chars
"""
if not str:
return ""
return string.join(['%' + s.encode('hex') for s in str], '')
def urldecode(str):
if not str:
return ""
return urllib.unquote(str)
def dictToURLParams(d):
if d:
return '&'.join([i + '=' + urlencode(v) for i,v in d.items()])
else:
return None
##
## XML escaping and unescaping
##
def xml_escape(s):
raise Exception('not implemented yet')
def xml_unescape(s):
new_s = s.replace('<','<').replace('>','>')
return new_s
##
## XSS attack prevention
##
def xss_strip_all_tags(s):
"""
Strips out all HTML.
"""
return s
def fixup(m):
text = m.group(0)
if text[:1] == "<":
return "" # ignore tags
if text[:2] == "&#":
try:
if text[:3] == "&#x":
return unichr(int(text[3:-1], 16))
else:
return unichr(int(text[2:-1]))
except ValueError:
pass
elif text[:1] == "&":
import htmlentitydefs
entity = htmlentitydefs.entitydefs.get(text[1:-1])
if entity:
if entity[:2] == "&#":
try:
return unichr(int(entity[2:-1]))
except ValueError:
pass
else:
return unicode(entity, "iso-8859-1")
return text # leave as is
return re.sub("(?s)<[^>]*>|&#?\w+;", fixup, s)
random.seed()
def random_string(length=20):
random.seed()
ALPHABET = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789'
r_string = ''
for i in range(length):
r_string += random.choice(ALPHABET)
return r_string
def get_host():
return settings.SERVER_HOST
def get_prefix():
return settings.SERVER_PREFIX
##
## Datetime utilities
##
def string_to_datetime(str, fmt="%Y-%m-%d %H:%M"):
if str == None:
return None
return datetime.datetime.strptime(str, fmt)
##
## email
##
from django.core import mail as django_mail
def send_email(sender, recpt_lst, subject, body):
# subject up until the first newline
subject = subject.split("\n")[0]
django_mail.send_mail(subject, body, sender, recpt_lst, fail_silently=True)
##
## raw SQL and locking
##
def one_val_raw_sql(raw_sql, values=[]):
"""
for a simple aggregate
"""
from django.db import connection, transaction
cursor = connection.cursor()
cursor.execute(raw_sql, values)
return cursor.fetchone()[0]
def lock_row(model, pk):
"""
you almost certainly want to use lock_row inside a commit_on_success function
Eventually, in Django 1.2, this should move to the .for_update() support
"""
from django.db import connection, transaction
cursor = connection.cursor()
cursor.execute("select * from " + model._meta.db_table + " where id = %s for update", [pk])
row = cursor.fetchone()
# if this is under transaction management control, mark the transaction dirty
try:
transaction.set_dirty()
except:
pass
return row