最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

How do I prevent jinja2 from rendering bytes values with the "b" prefix and single quotes? - Stack Overflow

programmeradmin4浏览0评论

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:

  1. Jinja2 throws an error if someone tries to render bytes
  2. 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:

  1. Jinja2 throws an error if someone tries to render bytes
  2. Alternatively, Jinja2 automatically converts the bytes to strings using decode("utf8"), but I'd prefer the former.
Share Improve this question asked Mar 24 at 13:36 Alessandro MammanaAlessandro Mammana 11
Add a comment  | 

1 Answer 1

Reset to default 0

Although 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 + '' }}

与本文相关的文章

发布评论

评论列表(0)

  1. 暂无评论