Python全系列 教程
3567个小节阅读:5930.6k
目录
鸿蒙应用开发
C语言快速入门
JAVA全系列 教程
面向对象的程序设计语言
Python全系列 教程
Python3.x版本,未来主流的版本
人工智能 教程
顺势而为,AI创新未来
大厂算法 教程
算法,程序员自我提升必经之路
C++ 教程
一门通用计算机编程语言
微服务 教程
目前业界流行的框架组合
web前端全系列 教程
通向WEB技术世界的钥匙
大数据全系列 教程
站在云端操控万千数据
AIGC全能工具班
A A
White Night
渲染模版就是在Flask_RESTful的类视图中要返回html片段代码,或者是整个html文件代码。
如何需要浏览器渲染模板内容应该使用api.representation
这个装饰器来定义一个函数,
在这个函数中,应该对html
代码进行一个封装,再返回。
注意
api.representation装饰器修饰的函数必须返回一个Response对象
xxxxxxxxxx
from flask import Flask,render_template,Response
from flask_restful import Api,Resource
import json
app = Flask(__name__)
# 如果想要前端的中文不再是\u这样的编码,可以加如下参数配置
app.config['RESTFUL_JSON'] = dict(ensure_ascii=False)
api = Api(app)
class HomeView(Resource):
def get(self):
return {"msg":"这个是个人主页"}
class IndexView(Resource):
def get(self):
return render_template('index.html')
api.add_resource(IndexView,'/index/')
api.add_resource(HomeView,'/home/')
@api.representation('text/html')
def out_html(data,code,headers):
# 必须返回一个response对象
if isinstance(data, str):
resp = Response(data)
return resp
else:
return Response(json.dumps(data,ensure_ascii=False).encode('gbk'))
if __name__ == '__main__':
app.run(debug=True)
实时学习反馈
1. 在Flask-RESTFul中,对于渲染模板说法错误的是?
A RESTFul可以直接渲染模板
B RESTFul默认返回模板,并不能渲染,只是返回代码
C 通过api.representation('text/html')
修饰的函数必须返回一个Response对象
D 通过api.representation('text/html')
修饰的函数里处理返回内容
答案
1=>A