-
Notifications
You must be signed in to change notification settings - Fork 1
/
webtool.py
executable file
·57 lines (49 loc) · 1.74 KB
/
webtool.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
#!/usr/bin/env python
# REQUEST_METHOD = GET/POST
# REQUEST_URI = /mai/linkoe
# IP = REMOTE_ADDR
class WebToolException(Exception):
"""
Raised on an exception in the WebTool.
"""
class WebTool(object):
"""
The WebTool class provides me with the required MiddleWare utilities.
Current functionality:
- URL-Based function calling and argument parsing.
"""
def __init__(self):
self.rules = {}
pass
def add_rule(self, rule, func, varnames):
"""
Add a new rule. The rule has to be a regex object. (Use re.compile)
func is called with varnames amount of named arguments.
"""
if rule in self.rules:
raise WebToolException('Rule %s already exists' % rule)
self.rules[rule] = {'func': func, 'vars': varnames}
def add_rules(self, rules, funcs, varnames):
for rule, func, vnames in zip(rules, funcs, varnames):
self.add_rule(rule, func, vnames)
def apply_rule(self, url, env):
"""
apply_rule finds an appropriate rule and applies it if found.
"""
for rule, fv in self.rules.iteritems():
m = rule.match(url)
if m:
l = [x for x in m.groups()]
if len(l) != len(fv['vars']):
raise WebToolException('Matches does not equal variable \
amount')
return fv['func'](env=env, **dict(zip(fv['vars'], l)))
return None
def read_post_data(env):
postdata = env['wsgi.input'].read()
splitdata = [x.split('=') for x in postdata.split('&')]
try:
data = dict(splitdata)
except (TypeError, ValueError):
data = None
return data