Last active
August 29, 2015 14:00
-
-
Save 4b5ent1/11211904 to your computer and use it in GitHub Desktop.
pyramid.events.BeforeRender: fix the UnicodeDecodeError exception on rendering template
This file contains 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
# encoding:utf-8 | |
u""" | |
用比较恶心的办法解决模板渲染时出现 UnicodeDecodeError 的问题 | |
This subscriber try to convert all <str> to <unicode> | |
functional available for Chameleon, Jinja2, and Mako | |
[2014-04-23] work with: | |
chameleon==2.14 | |
pyramid_chameleon==0.1 | |
jinja2==2.7.2 | |
pyramid_jinja2==1.10 | |
mako==0.9.1 | |
pyramid_mako==0.3.1 | |
""" | |
from pyramid.interfaces import IRendererFactory | |
def tmpl_unicode(event): | |
''' event ~ pyramid.events.BeforeRender | |
fix the UnicodeDecodeError | |
: renderer.template.encoding ~ chameleon.PageTemplate.render | |
: renderer.environment ~ jinja2.environment.Environment.finalize | |
: renderer.lookup ~ mako.lookup.TemplateLookup.template_args | |
''' | |
info = event['renderer_info'] | |
renderer_factory = info.registry.getUtilitiesFor(IRendererFactory) | |
factory = dict(renderer_factory) | |
# if info.type == '.pt': | |
if factory[info.type] == factory['.pt']: | |
info.renderer.template.encoding = 'utf-8' | |
elif factory[info.type] == factory['.jinja2']: | |
env = info.renderer.environment | |
env.finalize = lambda x: \ | |
unicode(x,'utf-8') if isinstance(x, str) else x | |
elif factory[info.type] == factory['.mako']: | |
args = info.renderer.lookup.template_args | |
filters = args['default_filters'] | |
if 'decode.utf8' not in filters: # not 'decode.utf-8' | |
filters.insert(0, 'decode.utf8') # append will fail | |
# args['output_encoding'] = 'utf-8' | |
# args['encoding_errors'] = 'replace' | |
def includeme(config): | |
config.add_subscriber(tmpl_unicode, 'pyramid.events.BeforeRender') |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment