Flask适用于简单的接口请求
安装
pip install Flask
pip install Flask-RESTful
仅简单请求url,然后出发处理程序,返回处理结果
app.py代码如下
from flask import Flask,jsonify
from flask_restful import Api,Resource,request,reqparse
from sqlalchemy import create_engine
from local_settings import SQLALCHEM
import logging,datetime
logger=logging.getLogger('my_app')
app=Flask(__name__)
api=Api(app)
class ProceListAPI(Resource):
def __init__(self):
self.engine=create_engine(alchemy_conf,pool_size=5,max_overflow=0,pool_recycle=7*60) # 初始化全局的数据库连接池
self.reqparse=reqparse.RequestParser()
self.reqparse.add_argument('subid',action='append',dest='cart_code',type=int,required=True,help='subid is needed!',location='form')
self.reqparse.add_argument('description',type=str,default="",location='json') # 配置 哪些入参是什么格式,在什么位置,dest表示别名
supper(PriceListAPI,self).__init__()
def get(self): #flask的api类中的所有get请求经过 get方法 ,post请求 经过post方法
logger.warning('request form:{},num:{}'.format(request.args,type(request.args.get('subid'))))
cart_code = request.args.get('subid')
if not cart_code:
return {'error':'subid is Rquired!'}
cart_code=cart_code.split(',')
with self.engine.connect() as conn:
result = conn.execute('select distinct cart_code,price from price_store where collect_time>=curdate();')
datas=result.fetchall()
dup_dict={}
for d in datas:
if d[0] in cart_code:
dup_dict[d[0]]=(d[0],d[1])
return dup_dict
def post(self):
args=self.reqparse.parse_args()
cart_code=args['cart_code']
if not cart_code:
return {'error':'subid is Required!'}
return {'cart_code':cart_code}
api.add_resource(PriceListAPI,'./price/',endpoint='stores') #定义class类 对应的url
if __name__ == '__main__':
app.run(debug=True,port=5091,houst='0.0.0.0')
通过 python app.py就可以运行
给API class添加装饰器 ,在每次请求处理前先进行验证 ,如常用的验证 Headers中的Authorization字段
将app_key和app_secret融合 加密到组成 Authorization的值,来判断用户是否为合法用户
首先需要定义一个装饰器函数
from functools import wraps
def my_authenticate(func):
@wraps(func)
def wrapper(*args,**kwargs):
authen = request.headers.get('Authorization')
if not authen:
return {"code":403,"message":"Authenticated Error","data":{"isEnabled":0}},403
logger.warning('authen:%s'%(authen))
encode_authen=authen.encode('utf-8')
decode_authen = base64.b64decode(encode_authen)
app_key,app_sign,timestamp = decode_authen.decode('utf-8').split(';')
now = time.time()
if now-float(timestamp)>2*60:
return {"code":403,"message":"Authenticated expired","data":{"isEnabled":0}},403
if app_key != APP_KEY:
return {"code":403,"message":"Authenticate app_key error","data":{"isEnabled":0}},403
md5_obj = hashlib.md5()
content = app_key+APP_SECRET+timestamp
md5_obj.update(content.encode('utf-8'))
my_sign=md5_obj.hexdigest()
if app_sign==my_sign:
logger.info("authen ok!")
return func(*args,**kwargs)
return {"code":403,"message":"Authenticated Error","data":{"isEnabled":0}},403
return wrapper
然后在class ProceListAPI(Resource)的开头加上 decorators=[my_authenticate]
如:
class ProceListAPI(Resource):
decorators=[my_authenticate]
def __init__(self):
self.reqparse=reqparse.RequestParser()
....
这样就相当于给类ProceListAPI的每个方法都加上了装饰器 my_authenticate