Ticket #296: formencode_state.patch
| File formencode_state.patch, 3.0 KB (added by max, 3 years ago) |
|---|
-
pylons/decorators/__init__.py
9 9 from decorator import decorator 10 10 from formencode import htmlfill 11 11 from paste.util.multidict import UnicodeMultiDict 12 from pylons.i18n import _ as pylons_gettext 13 from formencode.api import _stdtrans as formencode_gettext 12 14 13 15 import pylons 14 16 … … 16 18 17 19 log = logging.getLogger(__name__) 18 20 21 def pylons_formencode_gettext(value): 22 """Translates a string ``value`` using pylons gettext first 23 and if that fails, formencode gettext. 24 25 This allows to "merge" localized error messages from built-in 26 FormEncode's validators with application-specific validators. 27 """ 28 trans = pylons_gettext(value) 29 if trans == value: # translation failed, try formencode 30 trans = formencode_gettext(value) 31 return trans 32 33 class PylonsFormEncodeState(object): 34 """A ``state`` for FormEncode validate API that includes 35 smart ``_`` hook. 36 37 The FormEncode library used by validate() decorator has some 38 provision for localizing error messages. In particular, it 39 looks for attribute ``_`` in the application-specific state 40 object that got passed to every ``.to_python()`` call. If it 41 is found, the ``_`` is assumed to be a gettext-like function 42 and is called to localize error messages. 43 44 One complication is that FormEncode ships with localized 45 error messages for standard validators so the user may want 46 to re-use them instead of gathering and translating 47 everything from scratch. To allow this, we pass as ``_`` a 48 function which looks up translation both in application and 49 formencode message catalogs. 50 """ 51 _ = staticmethod(pylons_formencode_gettext) 52 19 53 def jsonify(func, *args, **kwargs): 20 54 """Action decorator that formats output for JSON 21 55 … … 72 106 """ 73 107 def wrapper(func, self, *args, **kwargs): 74 108 """Decorator Wrapper function""" 109 state = PylonsFormEncodeState() 75 110 request = pylons.request._current_obj() 76 111 errors = {} 77 112 if post_only: … … 90 125 if schema: 91 126 log.debug("Validating against a schema") 92 127 try: 93 self.form_result = schema.to_python(decoded )128 self.form_result = schema.to_python(decoded, state) 94 129 except formencode.Invalid, e: 95 130 errors = e.unpack_errors(variable_decode, dict_char, list_char) 96 131 if validators: … … 101 136 for field, validator in validators.iteritems(): 102 137 try: 103 138 self.form_result[field] = \ 104 validator.to_python(decoded.get(field) )139 validator.to_python(decoded.get(field), state) 105 140 except formencode.Invalid, error: 106 141 errors[field] = error 107 142 if errors: