flask_restful渲染模版

渲染模版就是在 Flask_RESTful 的类视图中要返回 html 片段代码,或 者是整个html 文件代码。
如何需要浏览器渲染模板内容应该使用 api.representation 这个装饰器来定 义一个函数, 在这个函数中,应该对 html 代码进行一个封装,再返回。
注意
api.representation 装饰器修饰的函数必须返回一个 Response 对象

main.py

复制代码
from flask import Flask,render_template,Response
from flask_restful import Api,Resource
import json
app = Flask(__name__)

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('index2.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,code,headers):
        resp = Response(data)
        return resp 
    else:
        return Response(json.dumps(data,ensure_ascii=False)).encode('gbk')


if __name__=="__main__":
    app.run(debug=True)

index2.html

复制代码
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title></title>
</head>
<body>
    <h1>这是个模板内容</h1>
</body>
</html>

执行结果:

相关推荐
宸津-代码粉碎机1 分钟前
Spring 6.0+Boot 3.0实战避坑全指南:5大类高频问题与解决方案(附代码示例)
java·数据仓库·hive·hadoop·python·技术文档编写
傻啦嘿哟1 分钟前
Python自动整理音乐文件:按艺术家和专辑分类歌曲
数据库·python·分类
weixin_462446236 分钟前
基于 Flask + lunar-python 的农历转换 API 实战(公历 ↔ 农历 / 干支 / 生肖 / 节日)
python·flask·节日
weixin_5795996619 分钟前
编写一个程序,输入两个数字的加减乘除余数(Python版)
开发语言·python
liu****22 分钟前
02_Pandas_数据结构
数据结构·python·pandas·python基础
RFCEO41 分钟前
用手机写 Python程序解决方案
开发语言·python·智能手机·qpython环境安装
0思必得042 分钟前
[Web自动化] Requests模块基本使用
运维·前端·python·自动化·html·web自动化
AAA简单玩转程序设计1 小时前
救命!Python 这些基础操作居然能省一半工作量
python
Brduino脑机接口技术答疑1 小时前
TDCA 算法在 SSVEP 场景中:Padding 的应用对象与工程实践指南
人工智能·python·算法·数据分析·脑机接口·eeg
quant_19861 小时前
如何处理大规模行情数据:从源头到终端的实战教程
大数据·开发语言·经验分享·python·金融