Flask_RESTful之渲染模版


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) 

#使用flask-restful渲染模版 
class ListView(Resource): 
	def get(self): 
		return render_template('index.html') 

api.add_resource(ListView,'/list/') 

# 渲染模版经过修改后,能支持html和json 
@api.representation('text/html') 
def output_html(data,code,headers): 
	if isinstance(data,str): 
		# 在representation装饰的函数中,必须返回一个Response对象 
		resp =Response(data) 
		return resp 
	else: 
		return Response(json.dumps(data),mimetype='application/json')
		

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值