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>

执行结果:

相关推荐
清水白石0081 小时前
突破并行瓶颈:Python 多进程开销全解析与 IPC 优化实战
开发语言·网络·python
麦麦大数据1 小时前
M003_中药可视化系统开发实践:知识图谱与AI智能问答的完美结合
人工智能·flask·llm·vue3·知识图谱·neo4j·ner
Lupino2 小时前
IoT 平台可编程化:基于 Pydantic Monty 构建工业级智能自动化链路
python
清水白石0083 小时前
突破性能瓶颈:深度解析 Numba 如何让 Python 飙到 C 语言的速度
开发语言·python
yunhuibin5 小时前
AlexNet网络学习
人工智能·python·深度学习·神经网络
喵手6 小时前
Python爬虫实战:增量爬虫实战 - 利用 HTTP 缓存机制实现“极致减负”(附CSV导出 + SQLite持久化存储)!
爬虫·python·爬虫实战·零基础python爬虫教学·增量爬虫·http缓存机制·极致减负
一个处女座的程序猿O(∩_∩)O6 小时前
Python异常处理完全指南:KeyError、TypeError、ValueError深度解析
开发语言·python
was1726 小时前
使用 Python 脚本一键上传图片到兰空图床并自动复制链接
python·api上传·自建图床·一键脚本
好学且牛逼的马6 小时前
从“Oak”到“虚拟线程”:JDK 1.0到25演进全记录与核心知识点详解a
java·开发语言·python
shangjian0076 小时前
Python基础-环境安装-Anaconda配置虚拟环境
开发语言·python