flask restful 实现返回结果为 html

来源:互联网 发布:centos修改防火墙端口 编辑:程序博客网 时间:2024/05/16 09:38
flask restful 默认的返回结果为 json 类型,即使请求中带的消息头为 
  1. Accept:

    text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8
因为 flask restful 支持的mediatype仅为application/json,对应的处理函数为 output_json。
如果要输出 html 格式的内容,则需要自己添加处理对应mediatype的函数

from flask.ext.restful import Api, Resource, reqparsefrom flask import make_response

app = Flask(__name__)@app.after_requestdef after_request(response):    response.headers['Access-Control-Allow-Origin'] = '*'    return responseapi = Api(app)@api.representation("text/html")def out_html(data,code, headers=None):    resp = make_response(data, code)    resp.headers.extend(headers or {})    return resp
如红色部分所示。
参考文章:
http://www.pythondoc.com/Flask-RESTful/extending.html#id5
Content-Type的取值:
http://blog.sina.com.cn/s/blog_4e967c8b0100zxnj.html
单纯 flask 实现 html 返回的文章参考,使用了模板渲染
http://stackoverflow.com/questions/3811595/flask-werkzeug-how-to-attach-http-content-length-header-to-file-download
http://docs.jinkan.org/docs/flask/quickstart.html

0 0
原创粉丝点击