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

最新文章

  1. cxf+spring+数字签名开发webservice(一)
  2. 取数据的前N行
  3. UI课堂笔记
  4. BIEE 创建一个简单的分析(2)
  5. BZOJ4327 : JSOI2012 玄武密码
  6. Docker centos 安装syslog
  7. POJ 3678 Katu Puzzle (2-SAT,常规)
  8. Spring AOP--基于XML文件的配置
  9. 带你深入了解Web站点数据库的分布存储
  10. 使用Dataset
  11. Windows2008 VPN登录
  12. 写入soap消息以及与soap消息通信
  13. 添加用户useradd,给用户设置修改密码passwd,修改用户信息usermod,修改用户密码状态chage,删除用户userdel,查询用户及组id,切换用户su,查看当前环境变量env
  14. Android 技能图谱学习路线
  15. java面试一、1.4锁机制
  16. how to avoid inheritance abuse
  17. JS备忘
  18. Dockfile基本语法
  19. 第二章&#160;向量(a)接口与实现
  20. 负载均衡下 tomcat session 共享

热门文章

  1. eclipse集成springboot 插件(离线安装,含解决Cannot complete the install because one or more required items could)
  2. BaseAdapter的使用与优化
  3. SAP笔记
  4. x86和x64下指针的大小
  5. SQLite3的安装与使用
  6. autoprefixer 处理css3的前缀
  7. 51 Nod 1629 B君的圆锥
  8. Python基础之Python介绍
  9. Android_(消息提示)多种使用Toast的消息提示
  10. R-ets()