Python学习笔记(26)Mock接口开发---flask模块
一、Mock接口开发
知识背景:1.在实际的测试工作中,可能会接入第三方接口,如支付一类,或者未完成开发的接口,此时需要通过模拟接口来实现
2.测试中可能有多个小组,A开发的项目需要使用B项目组的数据库权限,但A并不想给B数据库权限,可通过模拟接口来传递数据
使用模块:flask--------------------轻量级web开发框架,通过pip install flask来安装模块
import json import flask server = flask.Flask(__name__)#将本python文件作为一个服务 @server.route('/login',methods=['post','get'])#变成一个接口,methods支持的请求类型 def login(): username = flask.request.values.get('username')#获取入参,支持params和form-data格式 password = flask.request.values.get('password')#获取入参 # flask.request.is_json#判断请求是否为json # flask.request.json_module.get('')#入参是json用这个 d = {'error_code':0,'msg':'登录成功','username':username,'password':password} return json.dumps(d,ensure_ascii=False)#字典转换为json,并保留汉字 @server.route('/api/pay',methods=['get']) def pay(): d = {'error_code':1,'msg':'支付成功'} return json.dumps(d,ensure_ascii=False) @server.route('/api/get_bill') def get_bill(): table_list = ['app_user','czm'] table_name = flask.request.values.get('table_name') limit = flask.request.values.get('limit',50) if table_name and table_name in table_list: sql = 'select *from %s limit %s'%(table_name,limit) result = tool.op_mysql(sql) data = {'error_code':0,'msg':'成功','data':result} else: data = {'error_code':-1,'msg':'没有权限查询该表'} return json.dumps(data, ensure_ascii=False) server.run(host='192.168.33.1',port=8000,debug=True) #debug=True后,表示修改代码后,自动重启服务,run()方法启动服务,且run只能写一次
#结合数据库操作的两个实例
import flask #web轻量级的开发框架 import json import hashlib import pymysql server = flask.Flask(__name__) def op_mysql(sql,one_tag=False): connect=pymysql.connect(host='127.0.0.1', user='jxz', password='123456', db='jxz', port=3306, charset='utf8', autocommit=True ) cursor = connect.cursor(pymysql.cursors.DictCursor) cursor.execute(sql) if one_tag: result = cursor.fetchone() else: result = cursor.fetchall() cursor.close() connect.close() return result @server.route('/api/payment') def payment(): data = {"code":0,"msg":"支付成功","amount":30000} return json.dumps(data,ensure_ascii=False) # # @server.route('/api/login') # def login(): # data = {"code":0,"msg":"登录成功"} # return json.dumps(data,ensure_ascii=False) #结合数据库 @server.route('/register',methods=['post']) def register(): username = flask.request.values.get('username') password = flask.request.values.get('password') cpwd = flask.request.values.get('cpwd') sql = 'select * from app_myuser where username="%s";'%username if username and password and cpwd: if password != cpwd: data = {'code':400,'msg':'两次输入密码不一致'} elif op_mysql(sql): data = {'code':401,'msg':'用户已存在'} else: password = hashlib.md5(password.encode()).hexdigest()#对密码进行MD5加密 insert_sql = 'insert into app_myuser (username,passwd) values ("%s","%s");'%(username,password) op_mysql(insert_sql) data = {'code':0,'msg':'注册成功'} else: data = {'code':400,'msg':'必填参数不能为空'} return json.dumps(data,ensure_ascii=False) #结合数据库,写一个登陆接口 @server.route('/login',methods=['post']) def login(): username = flask.request.values.get('username') password = flask.request.values.get('password') if username and password: sql = 'select * from app_myuser where username = "%s";'%username result = op_mysql(sql,True) if result: password = hashlib.md5(password.encode()).hexdigest()#对密码MD5加密 if password == result.get('passwd'): data = {'code':0,'msg':'登陆成功'} else: data = {'code':403,'msg':'账户/密码错误!'} else: data = {'code':401,'msg':'用户不存在'} else: data = {'code':401,'msg':'参数不能为空'} return json.dumps(data,ensure_ascii=False) server.run(host ='0.0.0.0',port=9999,debug=True)
代码优化:为login接口添加token
import time import flask #web轻量级的开发框架 import json import hashlib import pymysql import redis server = flask.Flask(__name__) def op_redis(key,value=None,expire=60*60*2): r =redis.Redis(host='127.0.0.1',password='H3r44^%*',decode_responses=True) if value: r.set(key,value,expire) else: r.get(key) def MD5(s,salt='238tew@#'):#定义一个加盐MD5加密方法 s = str(s) + salt result = hashlib.md5(s.encode()).hexdigest() return result def op_mysql(sql,one_tag=False): connect=pymysql.connect(host='127.0.0.1', user='jxz', password='123456', db='jxz', port=3306, charset='utf8', autocommit=True ) cursor = connect.cursor(pymysql.cursors.DictCursor) cursor.execute(sql) if one_tag: result = cursor.fetchone() else: result = cursor.fetchall() cursor.close() connect.close() return result #结合数据库,写一个登陆接口 @server.route('/login',methods=['post']) def login(): username = flask.request.values.get('username') password = flask.request.values.get('password') if username and password: sql = 'select * from app_myuser where username = "%s";'%username result = op_mysql(sql,True) if result: token = MD5(str(time.time()) + username)#token采用当前时间戳+username 后进行MD5加密后的数据 info = {'username':username,'id':result.get('id')}#token对应的key和value op_redis(token,json.dumps(info)) password = MD5(password)#对密码MD5加密 if password == result.get('passwd'): data = {'code':0,'msg':'登陆成功','token':token} else: data = {'code':403,'msg':'账户/密码错误!'} else: data = {'code':401,'msg':'用户不存在'} else: data = {'code':401,'msg':'参数不能为空'} return json.dumps(data,ensure_ascii=False)
优化:使用flask_cores模块配置支持跨越访问:
1 import flask 2 from flask_cors import CORS 3 4 server = flask.Flask(__name__) 5 CORS(server, supports_credentials=True) #初始化加载配置,支持跨越访问 6 7 server.config['JSON_AS_ASCII'] = False #配置json不被序列化为ascii,即保留中文 8 9 10 @server.route("/api/info", methods=["get", "put", "post", "delete"]) 11 def info(): 12 print(flask.request.args) 13 if flask.request.method == "GET": 14 data = {"code": 0, "msg": "操作成功", "data": {"roles": ["qa"], "avatar": "https://wpimg.wallstcn.com/f778738c-e4f8-4870-b634-56703b4acafe.gif", "name": "12320202020", "introduction": "1234@qq.com", "user": 1}} 15 else: 16 data = { 17 "code": 0, 18 "msg": "成功" 19 } 20 return flask.jsonify(data) # 相当于json-dumps,将字典转换为json字符串
只要在同一个局域网内,浏览器通过ip:port/....形式来访问接口