Python中如何开发一个登录接口和注册接口实例

 

#_author:'ZYB'
#data:2018/12/18
import redis
import flask
import json
import hashlib
def CheckUserInRedis(username):
    ip = 'XXXXXX'
    password = 'XXXXX'
    r = redis.Redis(host=ip,password=password,port=6379,db=15,decode_responses=True)
    key = 'zyb:'+username
    if key in r.keys():
        return True,key,r.get(key)
    else:
        return False,key,r.get(key)
def StoreInRedis(username,passwd):
    ip = 'XXXXXXX'
    password = 'XXXXXX'
    r = redis.Redis(host=ip, password=password, port=6379, db=15, decode_responses=True)
    key = 'zyb:'+username
    max = 0
    dict = {}
    for V in r.keys():
        res = json.loads(r.get(V))
        if max < res['id']:
            max = res['id']
    dict['id'] = max+1
    dict['username'] = username
    dict['passwd'] = passwd
    dict['is_admin'] = 1
    res = json.dumps(dict)
    r.set(key, res)
def my_md5(s):
    news = str(s).encode()
    m = hashlib.md5(news)
    return m.hexdigest()
server = flask.Flask(__name__)
@server.route('/login',methods=['get'])
def login():
    uname = flask.request.values.get('username')
    pd = flask.request.values.get('passwd')
    condition, key, v = CheckUserInRedis(uname)
    dict = json.loads(v)
    pwd = my_md5(pd)
    if condition:
        password = dict['passwd']
        if pwd == password:
            return '{"code":0,"msg":"恭喜%s登录!"}'%uname
        else:
            return '{"code":100,"msg":"密码错误!"}'
    else:
        return '{"code":200,"msg":"用户不存在!"}'
@server.route('/register',methods=['get'])
def register():
    uname = flask.request.values.get('username')
    pd = flask.request.values.get('passwd')
    cpd = flask.request.values.get('cpasswd')
    condition, key, v = CheckUserInRedis(uname)
    pwd = my_md5(pd)
    cpwd = my_md5(cpd)
    if uname and pd and cpd:
        if condition:
            return '{"code":300,"msg":"注册用户已存在!"}'
        elif pwd != cpwd:
            return '{"code":400,"msg":"两次密码不一致!"}'
        else:
            StoreInRedis(uname,pwd)
            return '{"code":0,"msg":"恭喜注册成功!"}'
    else:
        return '{"code":600,"msg":"必填参数未填,请看接口文档!"}'
server.run(host='0.0.0.0',port=8000,debug=True)

 

posted @ 2018-12-18 22:59  arraon  阅读(565)  评论(0编辑  收藏  举报