Flaskを使用していて、getリクエストからXMLファイルを返します。コンテンツタイプをxmlに設定するにはどうすればよいですか?
例えば
@app.route('/ajax_ddl')
def ajax_ddl():
xml = 'foo'
header("Content-type: text/xml")
return xml
このようにしてみてください:
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/
このようにシンプルに
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
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 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
もう1つ、誰も言及していないようです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>'