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>

执行结果:

相关推荐
2301_787312436 分钟前
Vue.js中Patch过程处理Teleport组件挂载位置的特殊逻辑
jvm·数据库·python
我鑫如一13 分钟前
性价比高的AI API中转站推荐企业
人工智能·python
Leinwin15 分钟前
GPT-5.5 Instant API接入教程:免费额度、速率限制与最佳实践
后端·python·flask
dfdfadffa15 分钟前
Golang Gin怎么做JWT登录认证_Golang Gin JWT教程【实用】
jvm·数据库·python
SilentSamsara16 分钟前
装饰器基础:从闭包到装饰器的自然演变
开发语言·前端·vscode·python·青少年编程·pycharm
m0_7364393019 分钟前
C#怎么实现MVVM模式 C#如何在WPF中使用MVVM设计模式分离视图和逻辑【架构】
jvm·数据库·python
zhoutongsheng26 分钟前
Chromebook适合用什么HTML函数工具_轻量化方案汇总【汇总】
jvm·数据库·python
万事大吉CC30 分钟前
【4】深入剖析 Django 之 MTV:ORM 系统核心原理
数据库·python·oracle·django·sqlite
今天长肉了吗1 小时前
风控指标平台实战:大数据量下如何设计分批处理
开发语言·数据库·python
2301_782040451 小时前
JavaScript中丢失的this:回调函数中指向改变的对策
jvm·数据库·python