七十九:flask.Restful之flask-Restful蓝图与渲染模板
2024-08-31 08:32:15
1、flask-Restful与蓝图结合使用
如果要在蓝图中使用flask-Restful,那么在创建Api对象的时候,就不应该使用app,而是蓝图,如果有多个蓝图,则需在每一个蓝图里面创建一个Api对象
from flask import Blueprint
from flask_restful import Api, Resource, fields, marshal_with from models import Article article_bp = Blueprint('article', __name__, url_prefix='/article')
api = Api(article_bp) class ArticleView(Resource):
# 定义要返回的数据结构
resource_fields = {
'title': fields.String, # article.title
'content': fields.String,
'author': fields.Nested({ # article.author
'username': fields.String, # article.author.username
'email': fields.String # article.author.email
}),
'tags': fields.List( # article.tags的list
fields.Nested({ # article.tags[n]
'id': fields.Integer, # # article.tags[n].id
'name': fields.String # # article.tags[n].name
})
)
} @marshal_with(resource_fields)
def get(self, article_id):
article = Article.query.get(article_id)
return article api.add_resource(ArticleView, '/<article_id>/', endpoint='article')
from flask import Flask
import config
from exts import db
from article import article_bp app = Flask(__name__)
app.config.from_object(config)
db.init_app(app)
app.register_blueprint(article_bp) if __name__ == '__main__':
app.run(debug=True)
2、使用flask-Restful渲染模板
由于flask-Restful的返回content-type默认是application/json,所以如果在flask-Restful的视图中想要返回html代码,或者是模板,那么就需要使用api.representation这个装饰器来声明content-type,并且定义一个函数,在这个函数中,应该对html代码进行一个封装,再返回
未使用api.representation装饰器声明content-type
class ListView(Resource):
def get(self):
return {'username': 'ListView.username'} api.add_resource(ListView, '/list/', endpoint='list')
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<h2>这是list.html</h2>
</body>
</html>
class ListView(Resource):
def get(self):
return render_template('list.html') api.add_resource(ListView, '/list/', endpoint='list')
使用api.representation装饰器声明content-type
@api.representation('text/html') # 当要返回的数据类型是这里定义的content-type的时候,会执行这里的函数
def output_html(data, code, headers):
""" 在representation装饰的函数中,必须放回一个Response对象 """
resp = Response(data)
return resp
最新文章
- cxf+spring+数字签名开发webservice(一)
- 取数据的前N行
- UI课堂笔记
- BIEE 创建一个简单的分析(2)
- BZOJ4327 : JSOI2012 玄武密码
- Docker centos 安装syslog
- POJ 3678 Katu Puzzle (2-SAT,常规)
- Spring AOP--基于XML文件的配置
- 带你深入了解Web站点数据库的分布存储
- 使用Dataset
- Windows2008 VPN登录
- 写入soap消息以及与soap消息通信
- 添加用户useradd,给用户设置修改密码passwd,修改用户信息usermod,修改用户密码状态chage,删除用户userdel,查询用户及组id,切换用户su,查看当前环境变量env
- Android 技能图谱学习路线
- java面试一、1.4锁机制
- how to avoid inheritance abuse
- JS备忘
- Dockfile基本语法
- 第二章&#160;向量(a)接口与实现
- 负载均衡下 tomcat session 共享