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>

执行结果:

相关推荐
wefly20171 小时前
纯前端架构深度解析:jsontop.cn,JSON 格式化与全栈开发效率平台
java·前端·python·架构·正则表达式·json·php
胡耀超1 小时前
Token的八副面孔:为什么“词元“不需要更好的翻译,而需要更多的读者
大数据·人工智能·python·agent·token·代币·词元
biubiubiu07062 小时前
Python 环境安装与 Linux 控制入门
linux·开发语言·python
第一程序员2 小时前
Python与前端集成:构建全栈应用
python·github
程序员小远3 小时前
Jmeter基础:Jmeter聚合报告详解
自动化测试·软件测试·python·测试工具·jmeter·测试用例·压力测试
凌波粒3 小时前
D2L学习笔记:安装、张量与数据处理
笔记·python·学习·pandas
coderlin_3 小时前
从0开始构建Claude Code
python·ai编程
副露のmagic4 小时前
字符串章节 leetcode 思路&实现
windows·python·leetcode
BackCatK Chen4 小时前
Python安装与VSCode配置完整教程(每步带截图说明)
vscode·python·python安装·vscode配置·python 3.9.10·嵌入式环境配置
硅基喵4 小时前
Python 入门:从“其他语言”到 Pythonic 思维的完整迁移手册
python