其实使用flask写接口,使用jsonify就很方便了,但是现在rest风盛行,所以flask也有相关的rest风格接口库,就是flask-resrful模块
直接在你的环境中安装这个模块就好了
pip install flask-restful
安装好了之后我们起一个flask项目,就可以使用了
我这里附上一段简单的代码:
from flask import Flask
from flask_restful import Resource,Api
app = Flask(__name__)
api = Api(app,prefix="/v1") # prefix表示路由前缀,为所有的API视图添加前缀
class ArticleApi(Resource): # 编写类视图时需要继承Resource
def get(self):
return {"hello":"world"}
api.add_resource(ArticleApi,"/article/",endpoint="article")
if __name__ == "__main__":
app.run(debug=True)
运行项目,使用Postman访问http://127.0.0.1:5000/v1/article/:
同flask一样,flask-restful同样支持返回任一迭代器,它将会被转换成一个包含原始 Flask 响应对象的响应:
class ArticleApi(Resource):
def get(self):
return {"hello":"world"},201,{"course":"python"}
flask-restful为我们提供了一个方法去验证请求参数:reqparse
from flask_restful import reqparse
class ArticleApi(Resource):
def get(self):
parse = reqparse.RequestParser()
parse.add_argument("title_id",type=int,help="title参数的值只能是int类型!")
# add_argument第一个参数代表请求的参数名称,type表示限定请求的参数类型,实际做的是将参数进行强制转换,如果可以就证明参数类型正确,help表示出错后的提示信息。
args = parse.parse_args(strict=True)
# parse_args会接收reqparse验证后的参数,以字典形式返回,strict=True表示限定参数只能是add_argument中添加的参数,否则返回400错误。
print(args)
return {"hello":"world"}
此时我们请求http://127.0.0.1:5000/v1/article/?title_id=abc:
当我们请求http://127.0.0.1:5000/v1/article/?title_id=1&id=1:
对于一个视图函数,可以指定好一些字段用于返回。在使用ORM模型或者自定义模型时,他会自动获取模型当中的相应字段,生成json数据返回给客户端,我们需要导入flask_restful.marshl_with装饰器,并且需要写一个字典来指定需要返回的字段,以及该字段的数据类型:
from flask_restful import fields,marshal_with
resource_fields = {
"id":fields.Integer,
"title":fields.String(default=None,attribute=None),
# 在返回字段时有时候没有值,我们可以使用default来设置一个默认值,例:default="默认标题"
# 如果我们在返回字段时想要以"headline"作为标题名返回给用户,但数据库中对应的字段名是"title",这时候我们可以使用attribute配置这种映射,例:"headline":fields.String(attribute="title")
"author_id":fields.String,
"author":fields.Nested({ # Nested可以进行嵌套字段
"username":fields.String,
"phone":fields.String
}),
"tag":fields.List(fields.Nested({
"id":fields.Integer,
"name":fields.String
}))
}
class ArticleApi(Resource):
@marshal_with(resource_fields)
def get(self):
article = Article.query.first()
return article # 返回article时,flask_restful会自动读取arctile模型上的id,title、author_id、tag以及author属性,组成一个json字符串返回给客户端。
# 查找字段时,会使用article.id,article.title,article.author_id,article.author.username,article.author.phone,article.tag.id,article.tag.name进行查找
class UpperString(fields.Raw):
def format(self, value):
return value.upper()
resource_fields = {
"value":UpperString
}
class ArticleApi(Resource):
@marshal_with(resource_fields)
def get(self):
return {"value":"abc"}
api.add_resource(ArticleApi,"/article/",endpoint="article")
flask-restful返回Json格式的数据,但有时候我们要渲染html模版,返回html格式的数据,可以使用representation()装饰器来实现:
@api.representation('text/html')
def output_html(data, code, headers=None):
"""输出函数有三个参数,data,code,以及 headers,data 是你从你的资源方法返回的对
象,code 是预计的 HTTP 状态码,headers 是设置在响应中任意的 HTTP 头。你的输出函
数应该返回一个 Flask 响应对象。"""
print(data)
response = make_response(data)
return response
此时就可以返回html页面了。
flask-restful还有一些中高级用法,具体可参考:http://www.pythondoc.com/Flask-RESTful/index.html。