Python Flask, how to set content type
I am using Flask and I return an XML file from a get request. How do I set the content type to xml ?
e.g.
@app.route('/ajax_ddl')
def ajax_ddl():
xml = 'foo'
header("Content-type: text/xml")
return xml
Solution 1:
Try like this:
from flask import Response
@app.route('/ajax_ddl')
def ajax_ddl():
xml = 'foo'
return Response(xml, mimetype='text/xml')
The actual Content-Type is based on the mimetype parameter and the charset (defaults to UTF-8).
Response (and request) objects are documented here: http://werkzeug.pocoo.org/docs/wrappers/
Solution 2:
As simple as this
x = "some data you want to return"
return x, 200, {'Content-Type': 'text/css; charset=utf-8'}
Hope it helps
Update: Use the method below because it will work with both python 2.x and python 3.x and it eliminates the "multiple header" problem (potentially emitting multiple, duplicate headers).
from flask import Response
r = Response(response="TEST OK", status=200, mimetype="application/xml")
r.headers["Content-Type"] = "text/xml; charset=utf-8"
return r