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>

执行结果:

相关推荐
weixin19970108016几秒前
《跨境二手ERP的3种对接模式:自研API / SaaS中间件 / 平台认证服务商,怎么选?》(附Python源码)
开发语言·python·中间件
B2_Proxy8 分钟前
Python 爬虫代理中间件开发:统一处理 403、429 与自动重试机制
python
学代码的CJY10 分钟前
Python序列类型详解
python
529宝宝起名网13 分钟前
用 Python 爬取古籍文献中的名字用例数据库:从二十四史到诗词文集的历史名字采集与分析
python
颜颜yan_8 小时前
ESP-IDF 鸿蒙 PC 适配全记录:打通 Python、构建工具链与 ESP32-P4 固件生成
python·华为·harmonyos
言乐68 小时前
Python加速器4跨境网络加速器
运维·服务器·开发语言·网络·python
weixin_440730508 小时前
线程02-并发串行-互斥锁-Semaphore-Event
python·thread
张小凡vip9 小时前
python--爬虫--经验积累的遇到的坑
开发语言·爬虫·python
毕业设计7039 小时前
(免费领源码) 基于微信小程序的预制菜商城的设计与实现25172-java、PHP、python、C#、小程序、大数据、单片机、网络工程等)
vue.js·python·mysql·微信小程序·pycharm·微信开发者工具·推荐算法
xifangge20259 小时前
AGENTS.md 怎么写?涵盖 Java、Python、Vue、Go 的 8 套开箱即用模板
java·vue.js·python