一个简单的用python 实现系统登录的http接口服务实例
用python 开发一个登录的http接口:
用户登录数据存在缓存redis里,登录时根据session判断用户是否已登录,session有效,则直接返回用户已登录,否则进mysql查询用户名及密码,用户信息匹配则返回登录成功并同时把seesion写进redis,session有效时间为40分钟。
具体实现如下:
项目结构:
start.py为启动文件:
import os,sys BASE_PATH = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) sys.path.insert(0,BASE_PATH) from lib.interface import server from conf.setting import SERVER_PORT server.run(host='0.0.0.0',port=SERVER_PORT,debug=True)
conf未配置文件,存放常量,setting.py内容:
MYSQL_HOST = '你的ip' MYSQL_PORT = 3306 SQL_DB = 'api' MYRDS_HOST = '你的ip' MYRDS_PORT = '6379' RDS_DB = 2 SERVER_PORT = 8888 # SALT = 'dsadsadsada' #
data为常用数据文件 如 msg.py内容:
NOT_NULL = { "msg":"必填参数不能为空", "code":400 }
lib为函数功能文件:
tool.py主要存放工具类函数或方法:
from conf.setting import MYSQL_HOST,MYSQL_PORT,SQL_DB,SALT,MYRDS_HOST,MYRDS_PORT,RDS_DB def md5_passwd(str): str=str+SALT import hashlib md = hashlib.md5() md.update(str.encode()) res = md.hexdigest() return res.upper() def conn_mysql(sql): import pymysql conn = pymysql.connect(host=MYSQL_HOST,user ='root',password ='123456',db=SQL_DB,charset='utf8',port=MYSQL_PORT) cur = conn.cursor(cursor=pymysql.cursors.DictCursor) cur.execute(sql) res = cur.fetchone() conn.commit() cur.close() conn.close() return res def my_json(dic): import json return json.dumps(dic,ensure_ascii=False)
interface.py为http接口服务:
import flask from lib.tools import conn_mysql,md5_passwd,my_json from conf.setting import MYRDS_HOST,MYRDS_PORT,RDS_DB from flask import request from data.msg import NOT_NULL server = flask.Flask(__name__) import redis @server.route('/login',methods =['post']) def login(): username = request.json.get("username") password = request.json.get("password") password = md5_passwd(password) if username and password: r1 = redis.Redis(host= MYRDS_HOST, port= MYRDS_PORT, password='123456', db=RDS_DB) keys = r1.keys() if username.encode() in keys: return '{"msg": "你已经登录", "code": 800}' else: sql = 'select id,username,password from user where username ="%s";' % username res = conn_mysql(sql) if not res: return '{code":200,"msg":"用户名不存在}' elif res['password'] == password: r1.setex(username,1,1000) return '{"code":200,"msg":"登录成功"}' else: return '{"code":400,"msg":"密码输入错误"}' else: return my_json(NOT_NULL)