Python Flask, cómo establecer el tipo de contenido
Estoy usando Flask y devuelvo un archivo XML desde una solicitud get. ¿Cómo configuro el tipo de contenido?
Por ejemplo
@app.route('/ajax_ddl')
def ajax_ddl():
xml = 'foo'
header("Content-type: text/xml")
return xml
7 answers
Intenta así:
from flask import Response
@app.route('/ajax_ddl')
def ajax_ddl():
xml = 'foo'
return Response(xml, mimetype='text/xml')
El Content-Type actual se basa en el parámetro mimetype y el conjunto de caracteres (el valor predeterminado es UTF-8).
Los objetos de respuesta (y solicitud) están documentados aquí: http://werkzeug.pocoo.org/docs/wrappers /
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2012-08-02 08:49:39
Tan simple como esto
x = "some data you want to return"
return x, 200, {'Content-Type': 'text/css; charset=utf-8'}
Espero que ayude
Actualizar: Utilice este método porque funcionará tanto con python 2.x y python 3.x
Y en segundo lugar también elimina el problema de encabezado múltiple.
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
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-02-04 16:52:01
Me gusta y voté positivamente la respuesta de @Simon Sapin. Sin embargo, terminé tomando una táctica ligeramente diferente y creé mi propio decorador:
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
Y úsalo así:
@app.route('/ajax_ddl')
@returns_xml
def ajax_ddl():
xml = 'foo'
return xml
Creo que esto es un poco más cómodo.
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2013-08-29 02:21:47
Utilice el método make_response para obtener una respuesta con sus datos. Luego establece el atributo mimetype. Finalmente devuelve esta respuesta:
@app.route('/ajax_ddl')
def ajax_ddl():
xml = 'foo'
resp = app.make_response(xml)
resp.mimetype = "text/xml"
return resp
Si usas Response
directamente, pierdes la oportunidad de personalizar las respuestas configurando app.response_class
. El método make_response
utiliza el app.responses_class
para hacer el objeto response. En esto puedes crear tu propia clase, añadir make tu aplicación la usa globalmente:
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
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2015-07-31 21:15:10
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
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2015-06-30 04:06:46
Normalmente no tienes que crear el Response
objeta a ti mismo porque make_response()
me encargaré de eso por ti.
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
Una cosa más, parece que nadie mencionó el after_this_request
, quiero decir algo:
Ejecuta una función después de esta petición. Esto es útil para modificar objetos de respuesta. A la función se le pasa el objeto response y tiene que devolver el mismo o uno nuevo.
Para que podamos hazlo con after_this_request
, el código debería tener este aspecto:
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>'
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2015-11-12 09:07:43
Puede probar el siguiente método (python3.6.2):
Caso uno:
@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
Caso dos:
@app.route('/hello')
def hello():
headers={ 'content-type':'text/plain' ,'location':'http://www.stackoverflow.com'}
return '<h1>hello world</h1>',301,headers
Estoy usando Matraz .Y si quieres devolver json,puedes escribir esto:
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)
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-05-14 12:50:02