from .cfg import config import uuid import aiomysql import sys HOST = config["db"]["host"] PORT = config["db"]["port"] USER = config["db"]["user"] PASSWD = config["db"]["passwd"] DB = config["db"]["db"] MAXSIZE = config["db"]["maxsize"] MINSIZE = config["db"]["minsize"] async def connect_db(): global db sys.stdout.write("connect db\n") db = await aiomysql.create_pool( host=HOST, port=PORT, user=USER, password=PASSWD, db=DB, maxsize=MAXSIZE, minsize=MINSIZE ) async def create_db(): async with db.acquire() as conn: await (await conn.cursor()).execute( "CREATE TABLE IF NOT EXISTS users (username VARCHAR(255) PRIMARY KEY, password VARCHAR(255), email VARCHAR(255), accoutpwd VARCHAR(255))" ) async def get_user(username: str): async with db.acquire() as conn: async with conn.cursor() as cur: await cur.execute("SELECT username, password FROM users WHERE username = %s", (username,)) result = await cur.fetchone() if result: return result[1] return None async def get_user_passwd(username: str): async with db.acquire() as conn: async with conn.cursor() as cur: await cur.execute("SELECT accoutpwd FROM users WHERE username = %s", (username,)) result = await cur.fetchone() if result: return result[0] return "" async def create_user(username: str, password: str, email: str): async with db.acquire() as conn: async with conn.cursor() as cur: # 检查用户是否已存在 await cur.execute("SELECT username FROM users WHERE username = %s", (username,)) if await cur.fetchone(): return 1 # 创建新用户 await cur.execute("INSERT INTO users (username, password, email, accoutpwd) VALUES (%s, %s, %s, %s)", (username, password, email, uuid.uuid4().hex)) await conn.commit() return 0 async def check_user(username: str): async with db.acquire() as conn: async with conn.cursor() as cur: # 检查用户是否已存在 await cur.execute("SELECT username FROM users WHERE username = %s", (username,)) if await cur.fetchone(): return 1 return 0 async def update_passwd(username: str, password: str): async with db.acquire() as conn: async with conn.cursor() as cur: await cur.execute("UPDATE users SET password = %s WHERE username = %s", (password, username)) await conn.commit() return 0 async def get_email(username: str): async with db.acquire() as conn: async with conn.cursor() as cur: await cur.execute("SELECT email FROM users WHERE username = %s", (username,)) result = await cur.fetchone() if result: return result[0] return None