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>

执行结果:

相关推荐
覆东流2 分钟前
第5天:Python字符串操作进阶
开发语言·后端·python
NotFound4864 分钟前
分享实战中Python Web 框架对比:Django vs Flask vs FastAPI
前端·python·django
kongba00728 分钟前
vibe coding的测试架构设计提示词V1.0
python
qq_2837200534 分钟前
2026 最新 Python+AI 零基础入门实战教程:从零搭建企业级人工智能项目
人工智能·python·#机器学习·#python #ai零基础·#大模型开发·#rag·#ai避坑
贵沫末38 分钟前
Python——图像处理项目Conda环境搭建
开发语言·python·conda
财经资讯数据_灵砚智能40 分钟前
基于全球经济类多源新闻的NLP情感分析与数据可视化(夜间-次晨)2026年4月22日
大数据·人工智能·python·信息可视化·自然语言处理
white-persist42 分钟前
逆向入门经典题:从 IDA 反编译坑点到 Python 解题详细分析解释
c语言·开发语言·数据结构·python·算法·逆向·安全架构
钝挫力PROGRAMER1 小时前
程序中事件机制的实现
java·后端·python·软件工程
U盘失踪了1 小时前
Python Playwright 安装
python
HappyAcmen1 小时前
7.函数封装思路
python