Skip to content

Commit b5d3af2

Browse files
committed
Merge branch 'lazyjson'
Conflicts: flask_babel/__init__.py
2 parents 7e18089 + 77e166a commit b5d3af2

2 files changed

Lines changed: 20 additions & 5 deletions

File tree

flask_babel/__init__.py

Lines changed: 18 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -30,7 +30,7 @@
3030
timezone = pytz.timezone
3131
UTC = pytz.UTC
3232

33-
from flask_babel._compat import string_types
33+
from flask_babel._compat import string_types, text_type
3434

3535

3636
class Babel(object):
@@ -591,6 +591,21 @@ def npgettext(context, singular, plural, num, **variables):
591591
return s if not variables else s % variables
592592

593593

594+
def make_json_lazy_string(func, *args, **kwargs):
595+
"""Like :method:`speaklater.make_lazy_string` but returns a subclass
596+
that provides an :method:`__html__` method. That method is used by
597+
:class:`flask.json.JSONEncoder` to serialize objects of unrecognized
598+
types.
599+
"""
600+
from speaklater import _LazyString
601+
602+
class JsonLazyString(_LazyString):
603+
def __html__(self):
604+
return text_type(self)
605+
606+
return JsonLazyString(func, args, kwargs)
607+
608+
594609
def lazy_gettext(string, **variables):
595610
"""Like :func:`gettext` but the string returned is lazy which means
596611
it will be translated when it is used as an actual string.
@@ -603,8 +618,7 @@ def lazy_gettext(string, **variables):
603618
def index():
604619
return unicode(hello)
605620
"""
606-
from speaklater import make_lazy_string
607-
return make_lazy_string(gettext, string, **variables)
621+
return make_json_lazy_string(gettext, string, **variables)
608622

609623

610624
def lazy_pgettext(context, string, **variables):
@@ -613,8 +627,7 @@ def lazy_pgettext(context, string, **variables):
613627
614628
.. versionadded:: 0.7
615629
"""
616-
from speaklater import make_lazy_string
617-
return make_lazy_string(pgettext, context, string, **variables)
630+
return make_json_lazy_string(pgettext, context, string, **variables)
618631

619632

620633
def _get_current_context():

tests/tests.py

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -218,9 +218,11 @@ def test_lazy_gettext(self):
218218
yes = lazy_gettext(u'Yes')
219219
with app.test_request_context():
220220
assert text_type(yes) == 'Ja'
221+
assert yes.__html__() == 'Ja'
221222
app.config['BABEL_DEFAULT_LOCALE'] = 'en_US'
222223
with app.test_request_context():
223224
assert text_type(yes) == 'Yes'
225+
assert yes.__html__() == 'Yes'
224226

225227
def test_list_translations(self):
226228
app = flask.Flask(__name__)

0 commit comments

Comments
 (0)