Flask_RESTful渲染模版
- 如果在
Flask_RESTful
的类视图中想要返回html
片段代码,或者是整个html
文件代码,即渲染模版 - 使用
api.representation
装饰器来定义一个函数 - 在这个函数中,应该对
html
代码进行一个封装,再返回。
from flask import url_for,render_template,Blueprint,make_response,Response
from flask_restful import Api,Resource,reqparse,inputs,fields,marshal_with
import json
news_bp = Blueprint('news',__name__,url_prefix='/news')
api = Api(news_bp)
class ListView(Resource):
def get(self):
return render_template('index.html')
api.add_resource(ListView,'/list/')
@api.representation('text/html')
def output_html(data,code,headers):
if isinstance(data,str):
resp =Response(data)
return resp
else:
return Response(json.dumps(data),mimetype='application/json')