homework登录和支付mock两个接口

# 需求分析:
# 1、接收账号、密码,从mysql数据库里校验账号密码,判断账号密码报错还是正常
# 2、账号密码正确之后,要产生session_id
# 3、session_id的格式是md5(username+timestamp+salt)
# 4、写到redis中session_id的格式是{'user_id': 1, 'username': 小黑}
# 5、登录成功要返回这个session_id
# 6、pay接口传入的money和session_id是必填项,校验money的合法性,session_id的格式校验
import json

import flask
import tools

server = flask.Flask(__name__)


@server.route('/login')
def login():
username = flask.request.values.get('username')
password = flask.request.values.get('password')
if not username or not password:
data = {'code': -1, 'msg': '用户名/密码不能为空!'}
else:
# new_password = tools.md5(password)
new_password = password
sql = 'select id, username, passwd,error_count from app_myuser where username="%s";' % username
result = tools.op_mysql(sql, False)
if result:
if result.get('error_count') > 5:
data = {'code': -1, 'msg': '用户名被锁定'}
elif new_password == result.get('passwd'):
update_sql = 'update app_myuser set error_count=0 where username="%s";' % username
tools.op_mysql(update_sql)
r = tools.get_redis()
user_keys = r.keys('%s*' % username) # 取出以username开头的key,如果已登录,每次返回同一个session_id
if user_keys: # user_keys类型是一个list,user_keys的值是['sunsj1b119c60717e45c3e3a5f2c1f9620b0c']
session_id = user_keys[0].lstrip(username) # 去掉左侧的用户名就是session_id
else: # 如果第一次登录,产生的session_id如下
session_id = tools.get_session_id(username)
user_info = json.dumps({'user_id': result.get('id'), 'username': username})
tools.my_redis(username + session_id, user_info) # 把username和session_id写到redis里
data = {'code': 0, 'msg': '登录成功', 'session_id': session_id}
else: # 密码不对的时候让error_count次数加1
update_sql = 'update app_myuser set error_count=error_count + 1 where username="%s";' % username
tools.op_mysql(update_sql)
data = {'code': -1, 'msg': '密码错误'}
else:
data = {'code': -1, 'msg': '用户不存在'}
return json.dumps(data, ensure_ascii=False, indent=4)


@server.route('/pay')
def pay():
session_id = flask.request.values.get('session_id')
money = flask.request.values.get('money')
if not session_id or not money:
data = {'code': -1, 'msg': 'session_id/money不能为空!'}
elif not tools.is_price(money):
data = {'code': -1, 'msg': '价格不合法'}
else:
r = tools.get_redis()
session_id_key = r.keys('*%s' % session_id) # session_id_key是['ssjbb084cd885a376b9ffb7496e84c74faf']
if session_id_key:
session_id = session_id_key[0] # session_id取到list中的字符串
else:
return json.dumps({"code": -1, "msg": "请登录"})
user_info = tools.my_redis(session_id) # 只传一个是get操作,取出{"user_id": 8586259, "username": "ssj"}
if user_info: # 如果取到了session_id
user_info = json.loads(user_info) # 把取出的session_id对应的value转成字典
user_id = user_info.get('user_id') # 从字典中取出user_id
sql = 'select balance from app_myuser where id=%s;' % user_id # 通过user_id查出balance
balance = tools.op_mysql(sql, False).get('balance') # 从字典中取出balance
money = float(money)
if balance >= money: # 余额大于等于传入的money
update_sql = 'update app_myuser set balance = balance - %s where id=%s;' % (money, user_id)
tools.op_mysql(update_sql)
data = {'code': 0, 'msg': '支付成功'}
else:
data = {'code': -1, 'msg': '余额不足'}
else:
data = {'code': -1, 'msg': '请登录'}
return json.dumps(data, ensure_ascii=False, indent=4)


server.run(debug=True, port=999)

tools.py里的代码如下:
import time
import hashlib
import pymysql
import redis


def op_mysql(sql, many=True):
db_info = {'user': 'jxz', 'password': '123456', 'host': '118.24.3.40', 'db': 'jxz', 'port': 3306,
'charset': 'utf8', 'autocommit': True}
try:
conn = pymysql.connect(**db_info) # 建立连接
except Exception as e:
print("mysql连接失败", e)
return False
cur = conn.cursor(pymysql.cursors.DictCursor) # 游标
try:
cur.execute(sql) # 执行sql语句,insert 、update 、delete
except Exception as e:
print("sql错误,%s" % e)
result = "sql错误,%s" % e
else:
if many:
result = cur.fetchall()
else:
result = cur.fetchone() # {''}
finally:
cur.close()
conn.close()
return result


def md5(s, salt=''):
new_s = str(s) + salt
m = hashlib.md5(new_s.encode())
return m.hexdigest()


def my_redis(k, v=None, expire=60*60*2):
r = redis.Redis(host='118.24.3.40', password='HK139bc&*', port=6379, db=0, decode_responses=True)
if v:
r.set(k, v, expire)
else:
result = r.get(k)
return result


def get_session_id(username):
session_id = '%s%s' % (username, time.time())
new_session_id = md5(session_id, '@#F@#fdsf')
return new_session_id


# def is_price(s):
# s = str(s)
# if s.isdigit():
# return True
# if s.count('.') == 1:
# left, right = s.split('.')
# if left.isdigit() and right.isdigit():
# return True
# return False


def is_price(s):
try:
price = float(s)
except Exception as e:
print("价格错误:%s" % e)
return False
return price


def get_redis(): # 调用这个函数,返回一个redis连接
return redis.Redis(host='118.24.3.40', password='HK139bc&*', port=6379, db=0, decode_responses=True)
posted @ 2020-05-26 09:38  laosun0204  阅读(280)  评论(0编辑  收藏  举报