Last active
December 28, 2015 10:59
-
-
Save satiani/7490106 to your computer and use it in GitHub Desktop.
How to work around the caching of wtforms validator message translations
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
from flask import Flask, request, jsonify | |
from flask.ext.wtf import Form, TextField, Email | |
from flask.ext.babel import get_translations, lazy_gettext as __ | |
from flask.json import JSONEncoder | |
from speaklater import make_lazy_string, is_lazy_string | |
class CustomTranslations(object): | |
def babel_gettext(self, s): | |
return get_translations().ugettext(s) | |
def babel_ngettext(self, singular, plural, n): | |
return get_translations().ungettext(singular, plural, n) | |
def gettext(self, s): | |
return make_lazy_string(self.babel_gettext, s) | |
def ngettext(self, singular, plural, n): | |
return make_lazy_string(self.babel_ngettext, singular, plural, n) | |
class I8nForm(Form): | |
def _get_translations(self): | |
return CustomTranslations() | |
class ExampleForm(I8nForm): | |
email = TextField(__('Email'), [Email()]) | |
# idea from https://gist.github.com/pvanliefland/6009424 | |
class LazyAwareJsonEncoder(JSONEncoder): | |
def default(self, o): | |
if is_lazy_string(o): | |
return unicode(o) | |
return super(LazyAwareJsonEncoder, self).default(o) | |
app = Flask(__name__) | |
app.json_encoder = LazyAwareJsonEncoder | |
@app.route('/submit', methods=['POST']) | |
def submit(): | |
form = ExampleForm(request.form) | |
if form.validate_on_submit(): | |
return jsonify(result='success') | |
else: | |
return jsonify(result='failure', errors=form.errors) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment