我使用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

其他回答

使用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  

发送文件时

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 Flask, render_template, make_response
app = Flask(__name__)

@app.route('/user/xml')
def user_xml():
    resp = make_response(render_template('xml/user.html', username='Ryan'))
    resp.headers['Content-type'] = 'text/xml; charset=utf-8'
    return resp

通常您不必自己创建Response对象,因为make_response()将为您处理它。

from flask import Flask, make_response                                      
app = Flask(__name__)                                                       

@app.route('/')                                                             
def index():                                                                
    bar = '<body>foo</body>'                                                
    response = make_response(bar)                                           
    response.headers['Content-Type'] = 'text/xml; charset=utf-8'            
    return response

还有一件事,似乎没有人提到after_this_request,我想说的是:

after_this_request

在这个请求之后执行一个函数。这对于修改响应对象非常有用。函数被传递给响应对象,并且必须返回相同的或新的响应对象。

所以我们可以用after_this_request来做,代码应该是这样的:

from flask import Flask, after_this_request
app = Flask(__name__)

@app.route('/')
def index():
    @after_this_request
    def add_header(response):
        response.headers['Content-Type'] = 'text/xml; charset=utf-8'
        return response
    return '<body>foobar</body>'

您可以尝试以下方法(python3.6.2):

案例一:

@app.route('/hello')
def hello():

    headers={ 'content-type':'text/plain' ,'location':'http://www.stackoverflow'}
    response = make_response('<h1>hello world</h1>',301)
    response.headers = headers
    return response

案例二:

@app.route('/hello')
def hello():

    headers={ 'content-type':'text/plain' ,'location':'http://www.stackoverflow.com'}
    return '<h1>hello world</h1>',301,headers

如果你想返回json,你可以这样写:

import json # 
@app.route('/search/<keyword>')
def search(keyword):

    result = Book.search_by_keyword(keyword)
    return json.dumps(result),200,{'content-type':'application/json'}


from flask import jsonify
@app.route('/search/<keyword>')
def search(keyword):

    result = Book.search_by_keyword(keyword)
    return jsonify(result)