导入需要的第三方模块
import flask
import tools
import json,redis
import random
server = flask.Flask(__name__)
#新建一个服务,把当前这个python文件当做一个服务
ip = '118.24.3.40'
password='HK139bc&*'
r = redis.Redis(host=ip,password=password,port=6379,db=10,
decode_responses=True)#连接redis
@server.route('/login',methods=['get'])
def hello():
uname = flask.request.values.get('username')
pd = flask.request.values.get('passwd')
# sql = 'select * from app_myuser where username="%s"'%uname
# res = tools.my_db(sql)
key='nhy:%s'%uname
res = r.get(key)
if res:
res = json.loads(res)
if tools.my_md5(pd) == res.get('passwd'):
res = {"code":0,"msg":"登录成功!"}
else:
res = {"code":1,"msg":"密码错误!"}
else:
res = {'code':2,"msg":"用户不存在"}
return json.dumps(res,ensure_ascii=False,indent=4)
@server.route('/reg',methods=['post'])
def reg():
uname = flask.request.values.get('username')
pd = flask.request.values.get('passwd')
cpd = flask.request.values.get('cpwd')
key='nhy:%s'%uname
res = r.get(key)
if res:
res = {'code': 2, "msg": "用户已存在"}
else:
md5_password = tools.my_md5(pd)
res = {'id':random.randint(100,9999),'username':uname,'passwd':md5_password,'is_admin':1}
r.set('nhy:%s'%uname,json.dumps(res))#
res = {"code":0,"msg":"注册成功!"}
return json.dumps(res,ensure_ascii=False,indent=4)
@server.route('/api/stu')
def get_stu():
username = flask.request.values.get('name')#默认get不到的话,返回的值就是None
age = flask.request.values.get('age')
if username and age:
sql = "select * from app_student where name='%s' and age='%s'" % (username, age)
elif not username and age:
sql = "select * from app_student where age='%s'" % age
elif username and not age:
sql = "select * from app_student where name='%s'" % username
else:
sql = "select * from app_student"
res = tools.my_db2(sql)
return json.dumps(res,ensure_ascii=False,indent=4)
server.run(host='0.0.0.0',port=8999,debug=True)
#ip:8000/login
#127.0.0.1