我使用Flask和我从get请求返回一个XML文件。如何设置内容类型为xml ?

e.g.

@app.route('/ajax_ddl')
def ajax_ddl():
    xml = 'foo'
    header("Content-type: text/xml")
    return xml

当前回答

发送文件时

from flask import send_file

@app.route("/graph", methods = ['GET'])
def grafh():
    return send_file('graph.png', mimetype='image/png', as_attachment=False)

如果您想预览它或下载它,请更改as_attachment

其他回答

试着这样做:

from flask import Response
@app.route('/ajax_ddl')
def ajax_ddl():
    xml = 'foo'
    return Response(xml, mimetype='text/xml')

实际的Content-Type基于mimetype参数和字符集(默认为UTF-8)。

响应(和请求)对象记录在这里:http://werkzeug.pocoo.org/docs/wrappers/

我喜欢并点赞了@Simon Sapin的回答。然而,我最终采取了稍微不同的策略,创建了我自己的装饰器:

from flask import Response
from functools import wraps

def returns_xml(f):
    @wraps(f)
    def decorated_function(*args, **kwargs):
        r = f(*args, **kwargs)
        return Response(r, content_type='text/xml; charset=utf-8')
    return decorated_function

这样使用它:

@app.route('/ajax_ddl')
@returns_xml
def ajax_ddl():
    xml = 'foo'
    return xml

我觉得这个稍微舒服一点。

就这么简单

x = "some data you want to return"
return x, 200, {'Content-Type': 'text/css; charset=utf-8'}

更新: 使用下面的方法,因为它适用于python 2。X和python 3。X,它消除了“多个头”问题(可能会发出多个重复的头)。

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

发送文件时

from flask import send_file

@app.route("/graph", methods = ['GET'])
def grafh():
    return send_file('graph.png', mimetype='image/png', as_attachment=False)

如果您想预览它或下载它,请更改as_attachment

使用make_response方法获取数据响应。然后设置mimetype属性。最后返回这个响应:

@app.route('/ajax_ddl')
def ajax_ddl():
    xml = 'foo'
    resp = app.make_response(xml)
    resp.mimetype = "text/xml"
    return resp

如果你直接使用Response,你就失去了通过设置app.response_class来自定义响应的机会。make_response方法使用app.responses_class来创建响应对象。在这里你可以创建你自己的类,添加,使你的应用程序全局使用它:

class MyResponse(app.response_class):
    def __init__(self, *args, **kwargs):
        super(MyResponse, self).__init__(*args, **kwargs)
        self.set_cookie("last-visit", time.ctime())

app.response_class = MyResponse