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

Flask Rest接口的更多相关文章

  1. Flask request接口获取参数

    Flask request接口获取参数   request.form.get("key", type=str, default=None) 获取表单数据, request.args ...

  2. python——flask常见接口开发(简单案例)

    python——flask常见接口开发(简单案例)原创 大蛇王 发布于2019-01-24 11:34:06 阅读数 5208 收藏展开 版本:python3.5+ 模块:flask 目标:开发一个只 ...

  3. Python直接改变实例化对象的列表属性的值 导致在flask中接口多次请求报错

    错误原理实例如下: class One(): list = [1, 2, 3] @classmethod def get_copy_list(cls): # copy一份list,这样对list的改变 ...

  4. Python flask模块接口开发学习总结

    引言 Flask 是一个简单且十分强大的Python web 框架.它被称为微框架,“微”并不是意味着把整个Web应用放入到一个Python文件,微框架中的“微”是指Flask旨在保持代码简洁且易于扩 ...

  5. Keras + Flask 提供接口服务的坑~~~

    最近在搞Keras,训练完的模型要提供个预测服务出来.就想了个办法,通过Flask提供一个http服务,后来发现也能正常跑,但是每次预测都需要加载模型,效率非常低. 然后就把模型加载到全局,每次要用的 ...

  6. pyhton【flask接口开发】

    使用flask进行接口开发 语言:Python3 框架:flask 在进行开发前首先得安装flask,然后才能使用.安装可以直接使用pip命令进行安装:pip install flask. 使用fla ...

  7. 使用Flask开发简单接口

    作为测试人员,在工作或者学习的过程中,有时会没有可以调用的现成的接口,导致我们的代码没法调试跑通的情况. 这时,我们使用python中的web框架Flask就可以很方便的编写简单的接口,用于调用或调试 ...

  8. Flask备注三(Context)

    Flask备注三(Context) Flask支持不同的应用场景下,对应不同的local context(本地上下文环境),用来提供当前环境下的资源.lcoal context和全局变量以及局部变量最 ...

  9. python框架(flask/django/tornado)比较

    一.对外数据接口 三者作为web框架,都是通过url映射对外的接口 flask:以decorator的形式,映射到函数中 django:以字典形式,映射到函数 tornado: 以字典形式,映射到类中 ...

随机推荐

  1. 中间人攻击,HTTPS也可以被碾压

    摘要: 当年12306竟然要自己安装证书... 原文:知道所有道理,真的可以为所欲为 公众号:可乐 Fundebug经授权转载,版权归原作者所有. 一.什么是MITM 中间人攻击(man-in-the ...

  2. bay——RAC 表空间时数据文件误放置到本地文件系统-介质恢复.txt

    RAC添加新表空间时数据文件误放置到本地文件系统的修正 于是我想11G 也兼容这些操作的方法,但是11G的新特性有一点就是可以直接支持ASM文件系统直接可以和本地文件系统进行文件的拷贝了,也就是有三种 ...

  3. Export Receives The Errors ORA-1555 ORA-22924 ORA-1578 ORA-22922 (Doc ID 787004.1)

    Export Receives The Errors ORA-1555 ORA-22924 ORA-1578 ORA-22922 (Doc ID 787004.1) APPLIES TO: Oracl ...

  4. 对于Python语音性能的一些个人见解

    虽然运行速度慢是 Python 与生俱来的特点,大多数时候我们用 Python 就意味着放弃对性能的追求.但是,就算是用纯 Python 完成同一个任务,老手写出来的代码可能会比菜鸟写的代码块几倍,甚 ...

  5. 四、读取一系列dcm图片,然后重新写入

    一.程序功能 读取一系列的CT dcm图片,然后重新写入到一个文件夹 二.代码 #pragma warning(disable:4996) #include "itkGDCMImageIO. ...

  6. java自定义函数调用

    一:主类中自定义函数 在主类中,如果想要在main函数中调用自定义的其他方法,则这个函数需要使用static关键字定义,否则会报错Cannot make a static reference to t ...

  7. IT兄弟连 Java语法教程 流程控制语句 循环结构语句1

    循环语句可以在满足循环条件的情况下,反复执行某一点代码,这段被重复执行的代码被称为循环体,当反复执行这个循环体时,需要在合适的时候把循环条件该为假,从而结束循环,否则循环将一直执行下去,形成死循环.循 ...

  8. Jenkins—Master/Slave模式

    Jenkins可部署在windows或者linux平台上,项目系统的用户多数为windows系统.如果Jenkins部署在linux上,而自动化任务要在windows平台执行,那么就需要使用Jenki ...

  9. 学习UML类图

    在类图中一共包含以下几种模型元素,分别是:类(class).接口(interface)以及类之间的关系. 1.类(class) 在面向对象编程中,类是对现象世界中一组具有相同特征的物体的抽象. 2.接 ...

  10. DatabaseLibrary -数据库操作

    操作数据库: Table Must Exist 验证表必须存在,存在则Pass,反之Fail Delete All Rows From Table 删除数据库中表的所有行 Execute Sql St ...