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的视图中想要返回html代码,或者是模板,name就需要使用api.representation这个装饰器来定义一个函数,在这个函数中,应该对html代码进行一个封装,再返回
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('text/html') # 当要返回的数据类型是这里定义的content-type的时候,会执行这里的函数
def output_html(data, code, headers):
""" 在representation装饰的函数中,必须放回一个Response对象 """
resp = Response(data)
return resp