-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathvalidation.py
115 lines (95 loc) · 2.48 KB
/
validation.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
#!/usr/bin/env python
#-*- coding: utf-8 -*-
from google.appengine.ext import webapp
from google.appengine.ext.webapp import template, util
import os
import logging
import re
RULES = {
'name': {
'required': {
'onerror': 'missingName'
},
'limit': {
'limit': 100,
'onerror': 'tooLongName'
}
},
'phone': {
'required': {
'onerror': 'missingPhone'
},
'type': {
'type': 'phone',
'onerror': 'incorrectPhone'
}
},
'email': {
'required': {
'onerror': 'missingName'
},
'type': {
'type': 'email',
'onerror': 'incorrectEmail'
}
}
}
def limit(val, args):
if len(val) > args['limit']:
return args['onerror']
def required(val, args):
if not val:
return args['onerror']
def type(val, args):
regexp = {
'phone': '^(\d{5,7}|(\(\d{3}\)|\d{3})\d{7}|\+\d{1,3}(\(\d{3}\)|\d{3})\d{7})$',
'email': '^[-.\w]+@(?:[a-z\d][-a-z\d]+\.)+[a-z]{2,6}$'
}[args['type']]
if not re.match(regexp, val):
return args['onerror']
def bridge(rule, val, args):
f = {
'limit': limit,
'required': required,
'type': type
}[rule]
return f(val, args)
class Main(webapp.RequestHandler):
def get(self):
path = os.path.join('index.html')
params = {
}
self.response.out.write(template.render(path, params))
def post(self):
if not self.__validateInput():
self.redirect('/error')
return
self.redirect('/ok')
def __validateInput(self):
for field in RULES.keys():
val = self.request.get(field)
for rule in RULES[field].keys():
# logging.info('field: %s, rule: %s, val: %s' % (field, rule, val))
# logging.info(RULES[field][rule])
error = bridge(rule, val, RULES[field][rule])
if error:
logging.info(error)
return False
return True
class Others(webapp.RequestHandler):
def get(self):
page = self.request.path[1:]
path = os.path.join('ok.html')
params = {
'label': 'Thank you!' if page == 'ok' else 'Error!'
}
try:
self.response.out.write(template.render(path, params))
except Exception:
pass
def main():
application = webapp.WSGIApplication([('/', Main), ('/.*', Others)],
debug=True)
util.run_wsgi_app(application)
if __name__ == '__main__':
main()