Flask框架之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')
		
发布了354 篇原创文章 · 获赞 4 · 访问量 7806

猜你喜欢

转载自blog.csdn.net/weixin_44733660/article/details/104060889