This repository has been archived by the owner on Jun 3, 2018. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 18
/
forms.py
75 lines (58 loc) · 2.12 KB
/
forms.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
# -*- coding: utf-8 -*-
import re
import tornado.locale
from tornado.escape import to_unicode
from wtforms import Form as wtForm
class Form(wtForm):
"""
Using this Form instead of wtforms.Form
Example::
class SigninForm(Form):
email = EmailField('email')
password = PasswordField('password')
class SigninHandler(RequestHandler):
def get(self):
form = SigninForm(self.request.arguments, locale_code=self.locale.code)
"""
def __init__(self, formdata=None, obj=None, prefix='', locale_code='en_US', **kwargs):
self._locale_code = locale_code
super(Form, self).__init__(formdata, obj, prefix, **kwargs)
def process(self, formdata=None, obj=None, **kwargs):
if formdata is not None and not hasattr(formdata, 'getlist'):
formdata = TornadoArgumentsWrapper(formdata)
super(Form, self).process(formdata, obj, **kwargs)
def _get_translations(self):
if not hasattr(self, '_locale_code'):
self._locale_code = 'en_US'
return TornadoLocaleWrapper(self._locale_code)
class TornadoArgumentsWrapper(dict):
def __getattr__(self, key):
try:
return self[key]
except KeyError:
raise AttributeError
def __setattr__(self, key, value):
self[key] = value
def __delattr__(self, key):
try:
del self[key]
except KeyError:
raise AttributeError
def getlist(self, key):
try:
values = []
for v in self[key]:
v = to_unicode(v)
if isinstance(v, unicode):
v = re.sub(r"[\x00-\x08\x0e-\x1f]", " ", v)
values.append(v)
return values
except KeyError:
raise AttributeError
class TornadoLocaleWrapper(object):
def __init__(self, code):
self.locale = tornado.locale.get(code)
def gettext(self, message):
return self.locale.translate(message)
def ngettext(self, message, plural_message, count):
return self.locale.translate(message, plural_message, count)