python_模拟登录支付接口
Posted xmb
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了python_模拟登录支付接口相关的知识,希望对你有一定的参考价值。
模拟登录、支付接口
1 import flask,json 2 import tools 3 4 server = flask.Flask(__name__) 5 #登录接口 6 @server.route(‘/login‘) 7 def login(): 8 username = flask.request.values.get(‘username‘) 9 password = flask.request.values.get(‘password‘) 10 if not username or not password: 11 data = {‘code‘:-1,‘msg‘:‘用户名或密码不能为空‘} 12 else: 13 new_password = tools.md5(password) 14 sql = ‘select id,username,passwd,error_count from app_myuser where username="%s";‘%username 15 result = tools.op_mysql(sql,False) 16 if result: 17 if result.get(‘error_count‘) > 5: 18 data = {"code":-1,"msg":"账号被锁定"} 19 elif new_password == result.get(‘passwd‘): 20 up_sql = ‘update app_myuser set error_count = 0 where username = "%s";‘%username 21 tools.op_mysql(up_sql) 22 r = tools.get_redis() 23 user_keys = r.keys(‘%s*‘%username) #返回的是list 24 #print(user_keys) 25 if user_keys: 26 sessionid = user_keys[0].lstrip(username) #取list的第0个元素,去除左边的username,得到sessionid 27 #print(sessionid) 28 else: 29 sessionid = tools.get_sessionid(username) 30 user_info = json.dumps({"user_id":result.get(‘id‘),"username":username}) #把字典转成字符串 31 tools.my_redis(username+sessionid,user_info) #把sessionid添加到redis 32 data = {"code":0,"msg":"登录成功","session_id":sessionid} 33 else: 34 up_sql = ‘update app_myuser set error_count = error_count + 1 where username="%s";‘%username 35 tools.op_mysql(up_sql) 36 data = {"code":0,"msg":"密码错误"} 37 else: 38 data = {"code":-1,"msg":"用户不存在"} 39 return json.dumps(data,ensure_ascii=False,indent=4) 40 41 #支付接口 42 @server.route(‘/pay‘) 43 def pay(): 44 sessionid = flask.request.values.get(‘sessionid‘) #从请求里获取到参数 45 money = flask.request.values.get(‘money‘) 46 if not sessionid or not money: 47 data = {"code":-1,"msg":"参数不能为空"} 48 elif not tools.is_price(money): 49 data = {"code":-1,"msg":"金额不合法"} 50 else: 51 r = tools.get_redis() 52 sessionid_key = r.keys(‘*%s‘%sessionid) #从redis获取符合传入sessionid的所有key,返回的是list 53 #print(‘sessionid_key‘,sessionid_key) 54 if sessionid_key: 55 sessionid = sessionid_key[0] #获取list的第0个元素 56 #print(‘sessionid‘,sessionid) 57 else: 58 return json.dumps({"code":-1,"msg":"请登录"}) 59 user_info = tools.my_redis(sessionid) #操作redis,根据key取到value,返回的是字符串(json) 60 #print(user_info) 61 if user_info: 62 user_info = json.loads(user_info) #把字符串(json)转成字典 63 #print(user_info) 64 user_id = user_info.get("user_id") 65 sql = ‘select balance from app_myuser where id = %s;‘%user_id 66 balance = tools.op_mysql(sql,False).get("balance") 67 money = float(money) 68 if balance >= money: 69 update_sql = ‘update app_myuser set balance = balance - %s where id = %s‘%(money,user_id) 70 tools.op_mysql(update_sql) 71 data = {"code":0,"msg":"支付成功"} 72 else: 73 data = {"code":0,"msg":"余额不足"} 74 else: 75 data = {"code":-1,"msg":"请登录"} 76 return json.dumps(data,ensure_ascii=False,indent=4) 77 78 79 server.run(debug=True)
以上是关于python_模拟登录支付接口的主要内容,如果未能解决你的问题,请参考以下文章