注册两次同名再登录
(每道题开头都有同一段:open_db() 建一个内存 SQLite 库、含 users / notes / files 三张表、交回连接;执行 SQL 用 conn.execute(SQL, 参数元组),取一行用 .fetchone()、取全部用 .fetchall()、新行主键用 .lastrowid。判题机自带 sqlite3。)
(这一节还有:hash_pw 把密码变定长摘要、register(名字 UNIQUE,重名交回 False)、login(名字在且密码摘要对上才 True)。)
用同名注册两次、再用对的和错的密码各登录一次:
import sqlite3
def open_db():
"""建一个内存 SQLite 库,含 users / notes / files 三张表,交回连接。"""
conn = sqlite3.connect(":memory:")
conn.execute("CREATE TABLE users(id INTEGER PRIMARY KEY, name TEXT UNIQUE, pw TEXT)")
conn.execute("CREATE TABLE notes(id INTEGER PRIMARY KEY, uid INTEGER, text TEXT)")
conn.execute("CREATE TABLE files(id INTEGER PRIMARY KEY, uid INTEGER, name TEXT, size INTEGER)")
return conn
import hashlib
def hash_pw(pw):
"""把明文密码变成定长摘要(不明文存库)。"""
return hashlib.sha256(pw.encode()).hexdigest()[:16]
def register(conn, name, pw):
"""注册:名字 UNIQUE,重名交回 False,成功交回 True。"""
try:
conn.execute("INSERT INTO users(name, pw) VALUES(?, ?)", (name, hash_pw(pw)))
return True
except sqlite3.IntegrityError:
return False
def login(conn, name, pw):
"""登录:名字存在且密码摘要对上才交回 True。"""
row = conn.execute("SELECT pw FROM users WHERE name=?", (name,)).fetchone()
return row is not None and row[0] == hash_pw(pw)
c = open_db()
a = register(c, "amy", "pw")
b = register(c, "amy", "pw2")
print(str(a) + "/" + str(b) + "/" + str(login(c, "amy", "pw")) + "/" + str(login(c, "amy", "x")))
全部评论