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>

执行结果:

相关推荐
ShoreKiten2 小时前
ctfshowweb入门 SSTI模板注入专题保姆级教程(二)
web安全·flask·ssti·ctfshow
zchxzl2 小时前
亲测2026京津冀专业广告展会
大数据·人工智能·python
~央千澈~2 小时前
抖音弹幕游戏开发之第19集:课程总结与答疑·优雅草云桧·卓伊凡
python·pygame
小雨中_3 小时前
3.5 ReMax:用 Greedy 作为基线的 REINFORCE + RLOO
人工智能·python·深度学习·机器学习·自然语言处理
overmind3 小时前
oeasy Python 116 用列表乱序shuffle来洗牌抓拍玩升级拖拉机
服务器·windows·python
A懿轩A3 小时前
【Java 基础编程】Java 枚举与注解从零到一:Enum 用法 + 常用注解 + 自定义注解实战
java·开发语言·python
SmartBrain4 小时前
FastAPI实战(第二部分):用户注册接口开发详解
数据库·人工智能·python·fastapi
开发者导航4 小时前
【开发者导航】多功能生成模型开发工具:Diffusers 详细介绍
人工智能·python·学习·macos·信息可视化
ん贤4 小时前
Scrapy 嵌入 FastAPI 的坑:Asyncio/Twisted 桥接 + 代理池设计
python·scrapy·fastapi
岱宗夫up4 小时前
从代码模式到智能模式:AI时代的设计模式进化论
开发语言·python·深度学习·神经网络·自然语言处理·知识图谱