'how to set the content-type and character set in flask when use render_template?

I'm using flask and I user render_template() to render the output HTML. I get some unknown characters when show the page due to the header content type and character set of the page.

Content-Type: text/html; charset=utf-8

I need to know how to pass the content-type and character set to the header of the template when using render_template() function?



Solution 1:[1]

For example:

my_vars = { 'foo': 'bar', 'fish': 42 }
response = make_response(render_template('index.html', my_vars))
response.headers['Content-Type'] = 'text/html; charset=ISO-8859-1'
return response

Note: While this allows you to set the charset, I strongly advise you to use UTF-8 for your templates. Flask, Jinja2 and Werkzeug (all three are involved when you render and server a page) all assume everything is UTF-8. You will most probably get burnt at some point later down the line if you use something else than UTF-8.

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