13

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')

1 Answer 1

0

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.

Sign up to request clarification or add additional context in comments.

3 Comments

In my opinion, this is so weird for Template class in jinja2. Maybe there are some other sceneries that I do not understand for this mode.
Hello, I have no template file reading in my code: flask takes care of it in render_template
Hi, at this time maybe you need to check the real parameter for constructing Template instance or something other like this. If you put <class 'bytes'> type you get wrong result. If you put <class 'str'> type, everything works fine.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.