flask restful 实现返回结果为 html

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, reqparse
from flask import make_response

app = Flask(__name__)
@app.after_request
def after_request(response):
    response.headers['Access-Control-Allow-Origin'] = '*'
    return response
api = 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

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值