2024-04-23 08:26:47 发布
网友
我正在使用Flask,并从get请求返回一个XML文件。如何将内容类型设置为xml?
例如
@app.route('/ajax_ddl') def ajax_ddl(): xml = 'foo' header("Content-type: text/xml") return xml
我喜欢并支持西蒙·萨平的回答。然而,我最终采取了一种稍微不同的策略,并创建了自己的装饰器:
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
我觉得这样稍微舒服一点。
这样试试:
from flask import Response @app.route('/ajax_ddl') def ajax_ddl(): xml = 'foo' return Response(xml, mimetype='text/xml')
实际的内容类型基于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
我喜欢并支持西蒙·萨平的回答。然而,我最终采取了一种稍微不同的策略,并创建了自己的装饰器:
使用它:
我觉得这样稍微舒服一点。
这样试试:
实际的内容类型基于mimetype参数和字符集(默认为UTF-8)。
这里记录了响应(和请求)对象:http://werkzeug.pocoo.org/docs/wrappers/
就这么简单
希望有帮助
更新: 使用此方法,因为它将同时适用于python 2.x和python 3.x
其次,它还消除了多报头问题。
相关问题 更多 >
编程相关推荐