admin管理员组文章数量:1405624
in a Jinja2 template like "Tell me something: {{s}}", and with s
as a bytes value like s = b"foo"
, the rendered template will look like "Tell me something: b'foo'".
How do I avoid this behavior?
Using filters or preprocessing the data does not help in my case, because I'd like to use jinja2 as a building block of something else, and I don't have full control of the input data and of the templates. I am pretty sure this will become an extremely common mistake in my application so I'd like to prevent that.
The desired behavior is that:
- Jinja2 throws an error if someone tries to render bytes
- Alternatively, Jinja2 automatically converts the bytes to strings using
decode("utf8")
, but I'd prefer the former.
in a Jinja2 template like "Tell me something: {{s}}", and with s
as a bytes value like s = b"foo"
, the rendered template will look like "Tell me something: b'foo'".
How do I avoid this behavior?
Using filters or preprocessing the data does not help in my case, because I'd like to use jinja2 as a building block of something else, and I don't have full control of the input data and of the templates. I am pretty sure this will become an extremely common mistake in my application so I'd like to prevent that.
The desired behavior is that:
- Jinja2 throws an error if someone tries to render bytes
- Alternatively, Jinja2 automatically converts the bytes to strings using
decode("utf8")
, but I'd prefer the former.
1 Answer
Reset to default 0Although jinja2 doesn't offer a direct way to test if a variable is a bytes object rather than a string, one easy workaround is to concatenate the variable with an empty string to raise a TypeError: can't concat str to bytes
when given a bytes object:
Tell me something: {{ s + '' }}
本文标签:
版权声明:本文标题:How do I prevent jinja2 from rendering bytes values with the "b" prefix and single quotes? - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1744248870a2597152.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论