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>

执行结果:

相关推荐
测试199825 分钟前
使用Python自动化生成接口测试用例
自动化测试·软件测试·python·测试工具·职场和发展·测试用例·接口测试
智算菩萨1 小时前
【Pygame】第10章 游戏状态管理与场景切换机制
python·游戏·pygame
songcream11 小时前
TensorFlow的一些基本概念
人工智能·python·tensorflow
AI逐月2 小时前
解决 ComfyUI 插件安装后 Nanobind 报错问题:soxr 版本冲突原理解读
开发语言·python
AC赳赳老秦2 小时前
Windows 系统 OpenClaw 执行策略报错及管理员权限设置深度解析与实操指南
运维·人工智能·python·django·自动化·媒体·openclaw
软件开发技术深度爱好者3 小时前
用python + pillow实现GUI界面图片GUI处理工具
开发语言·python
FreakStudio3 小时前
ESP32 实现在线动态安装库和自动依赖安装-使用uPyPI包管理平台
python·单片机·嵌入式·面向对象·电子diy·sourcetrail
别抢我的锅包肉3 小时前
【FastAPI】 响应类型详解:从默认 JSON 到自定义响应
python·fastapi
智算菩萨3 小时前
【Tkinter】15 样式与主题深度解析:ttk 主题系统、Style 对象与跨平台样式管理实战
开发语言·python·ui·ai编程·tkinter