'Jinja2 template in Python 3 renders bytes with "b" prefix and quotes
I'm upgrading a Flask app from python2
to python3
,
Jinja2
now renders bytes with trailing b and single quotes, e.g. b'a123'
while I need them rendered as a123
.
This happens with all urlsafe strings which came as string [not unicode
] in python2 and were rendered as needed. Now they are bytes
I would like to avoid checking type every time and adding .decode('utf-8')
Solution 1:[1]
I encounter the same problem. Maybe it has been solved for you since the quetion has been past so long time.
In my problem, I open the file with 'rb' mode, and read()
method for file handler will return <type 'bytes'>
, so jinja2 Template.render()
will also return a string wrapper of string. (Just something you call it bytes with prefix 'b' and quotes)
with open("file.txt", "rb") as f:
text = f.read()
# type(text) -> <class 'bytes'>
template = Template(f.read())
template.render(kwargs)
After I modify the open mode with 'r', this time everything works as expected.
with open("file.txt", "r") as f:
text = f.read()
# type(text) -> <class 'str'>
template = Template(text)
template.render(kwargs)
So the problem is the type of real parameter in Template constructor function.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | litao3rd |