Restful API规范介绍
restful api是用于在前端与后台进行通信的一套规范。使用这个规范可以让前后端开发变得更加轻松。
协议
采用http或https协议
数据传输格式
数据之间传输的格式应该都使用json,而不使用xml
url连接
url连接中,不能有动词,并且对于一些名词,如果出现复数,那么应该在后面加s
HTTP请求的方法
PUT:在服务器上更新资源。(客户端提供所有改变后的数据)
PATCH:在服务器上更新资源。(客户端只提供需要改变的属性)
示例如下:
PUT/users/id/:更新某个id的用户的信息(需要提供用户的所有信息)
PATCH/users/id/:更新某个id的用户信息(只需要提供更改的信息)
状态码
用户发出的请求有误,服务器没有进行新建或修改数据的操作
用户请求不被服务器接收(比如服务器期望客户端发送某个字段,但是没有发送)
插件的基本使用
安装
pip install flask-restful
定义Restful的视图
使用flask-restful,那么定义视图函数的时候,就要继承自flask_restful.Resource类,然后再根据当前请求的method来定义相应的方法。比如期望客户端是使用get方法发送过来的请求,那么就定义一个get方法。类似于MethodView。
from flask import Flask,render_template,url_for
from flask_restful import Api,Resource
app = Flask(__name__)
# 用Api来绑定app
api = Api(app)
# Json数据
class IndexView(Resource):
def get(self,username=None):
return {"username":"angle"}
# 可以指定多个url
api.add_resource(IndexView,'/index/<username>/','/regist/','/',endpoint='index')
with app.test_request_context():
print(url_for('index',username='angle'))
if __name__ == '__main__':
app.run(debug=True)
endpoint是用来给url_for反转url的时候指定的。如果不写endpoint,那么将会使用视图的名字的小写作为endpoint。
add_resource的第二个参数是访问这个视图函数的url,这个url可以跟之前的route一样,可以传递参数,并且还有一点不同的是,这个方法可以传递多个url来指定这个视图函数
参数验证
Flask-Restful插件提供了类似wtForms来验证提交的数据是否合法的包,叫做reqparse。
基本用法:
parser = reqparse.RequestParser()
parser.add_argument('username',type=str,help='请输入用户名',required=True)
args = parser.parse_args()
add_argument可以指定这个字段的名字,这个字段的数据类型等。
参数
默认值,如果这个参数没有值,那么将使用这个参数指定的值
是否必须,如果这个参数没有值,那么将使用这个参数指定的值
这个参数的数据类型,如果指定,那么将使用指定的数据类型来强制转换提交上来
选项。提交上来的值只有满足这个选项中的值才符合验证通过,否则验证不通过
错误信息。如果验证失败后,将会使用这个参数指定的值作为错误信息
其中的type,可以使用python自带的一些数据类型,也可以使用flask_restful.inputs下的一些特定的数据累心来强制转换。
常用的:
url:会判断这个参数的值是否是一个url,如果不是,就会抛出异常
date:将这个字符串转换为datetime.date。如果转换不成功,则会抛出一个异常
from flask import Flask,render_template,url_for
from flask_restful import Api,Resource,reqparse,inputs
app = Flask(__name__)
# 用Api来绑定app
api = Api(app)
# Json数据
class LoginView(Resource):
def post(self):
# username
# password
parser = reqparse.RequestParser()
parser.add_argument('birthday', type=inputs, help='生日字段验证')
# # 验证日期
# parser.add_argument('birthday',type=inputs.date,help='生日字段验证')
# # 利用正则表达式验证手机号码
# parser.add_argument('telphone',type=inputs.regex(r'1[3578]\d{9}'))
# # 验证输入的url地址
# parser.add_argument('home_page',type=inputs.url,help='个人中心链接验证错误')
# parser.add_argument('username',type=str,help='用户名验证错误',default="angle")
# parser.add_argument('password',type=str,help=u'密码验证错误',required=True,trim=True)
# parser.add_argument('password',type=int,help=u'年龄验证错误')
# parser.add_argument('gender',type=str,choices=['male','female','secret'],help="性别验证错误")
args = parser.parse_args()
print(args)
return {"username":'angle'}
api.add_resource(LoginView,'/login/')
# with app.test_request_context():
# print(url_for('index',username='angle'))
if __name__ == '__main__':
app.run(debug=True)
标准化返回参数
对于一个视图函数,你可以指定好一些字段用于返回。以后可以使用ORM模型或者自定义的模型的时候,它会自动的获取模型中的相应的字段,生成json数据,然后再返回给客户端,这其中需要导入flask_restful.marshal_with
装饰器。并且需要写一个字典,来指示需要返回的字段,以及该字段的数据类型。
from flask_restful import Api,Resource,fields,marshal_with
class ProfileView(Resource):
resource_fileds = {
'username':fields.String,
'age':fields.Integer,
'school':fields.String
}
@marshal_with(resource_fields)
def get(self.user_id):
user = User.query.get(user_id)
return user
在get方法中,返回user的时候,flask_restful会自动的读取user模型上的username以及age还有school属性。组装成一个json格式的字符串返回给客户端。
重命名属性
# 更改content属性的命名
resource_fields = {
'title':fields.String,
'内容':fields.String(attribute='content'),
}
------------------------------------------------------
{
"title": "angle",
"内容": "angle"
}
默认值
resource_fields = {
'content':fields.String(default="angle"),
}
复杂结构
使用fields.List可以使字段的值为列表,使用fields.Nested可以使字段的值为字典
class ProfileView(Resource):
resource_field = {
'username':fields,String,
'age':fields.Integer,
'school':fields.String,
'tags':fields.List(fields.String),
'more':fields.Nested{ {
'signature': fields.String,
} }
}
细节
在蓝图中,如果使用'flask-restful',那么创建'Api'对象的时候,就不要再使用'app'了,而是使用蓝图
article_bp = Blueprint('article',__name__,url_prefix='/article')
api = Api(article_bp)
如果在'flask-restful'的视图中想要返回'html'代码或者是模板,那么就应该使用**'api.representation'**这个装饰器来定义一个函数,在这个函数中,应该对'html'代码进行一个封装,再返回
@api.representation('text/html')def output_html(data,code,headers): print(data) # 在representation装饰的函数中,必须返回一个Response对象 resp = make_response(data) return resp
class ListView(Resource): def get(self): return render_template('index.html')api.add_resource(ListView,'/list/',endpoint='list')