一個簡單的用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)

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM