数据库接口重构

This commit is contained in:
2024-04-15 15:19:56 +08:00
parent 372435d224
commit 79beba473e
7 changed files with 90 additions and 44 deletions

59
db/file.py Normal file
View File

@@ -0,0 +1,59 @@
import shortuuid
import db.util as util
# 查找文件信息
def searchByid(id: str):
conn = util.getConn()
c = conn.cursor()
cursor = c.execute("SELECT * FROM Metadata WHERE id = ?", (id,))
out = []
for row in cursor:
out.append(row)
conn.close()
return out
# 查找文件信息
def searchByname(filename: str):
conn = util.getConn()
c = conn.cursor()
cursor = c.execute("SELECT * FROM Metadata WHERE filename = ?", (filename,))
out = []
for row in cursor:
out.append(row)
conn.close()
return out
# 在数据库中添加一个新的文件记录
def new(filename: str):
suuid = shortuuid.random(8)
conn = util.getConn()
c = conn.cursor()
c.execute(
"""
INSERT INTO Metadata
(id, filename)
VALUES
(?, ?, ?);
""",
(suuid, filename),
)
conn.commit()
conn.close()
return suuid
# 获取文件元数据
def getMetadata(form: int, num: int):
conn = util.getConn()
c = conn.cursor()
cursor = c.execute(
"SELECT * FROM Metadata ORDER BY num desc LIMIT ?, ?", (form, num)
)
out = []
for row in cursor:
out.append(list(row))
conn.close()
return out

36
db/user.py Normal file
View File

@@ -0,0 +1,36 @@
import sqlite3, configparser
import db.util as util
config = configparser.ConfigParser()
config.read("./conf/app.ini")
def getConn():
return sqlite3.connect(config.get("database", "path"))
def new(username: str, password: int):
"新建用户"
conn = util.getConn()
c = conn.cursor()
c.execute(
"""
INSERT INTO User
(username, password)
VALUES
(?, ?);
""",
(username, password),
)
conn.commit()
conn.close()
def check(username: str, password: int):
"判断用户信息是否正确"
conn = util.getConn()
c = conn.cursor()
cursor = c.execute("SELECT * FROM User WHERE username = ? AND password = ?", (username, password))
if cursor.fetchone() is None:
return False
return True

33
db/util.py Normal file
View File

@@ -0,0 +1,33 @@
import sqlite3, configparser
config = configparser.ConfigParser()
config.read("./conf/app.ini")
def getConn():
return sqlite3.connect(config.get("database", "path"))
def init():
conn = getConn()
c = conn.cursor()
c.execute(
"""
CREATE TABLE IF NOT EXISTS Metadata (
num INTEGER PRIMARY KEY AUTOINCREMENT,
id TEXT NOT NULL,
filename TEXT NOT NULL
);
"""
)
c.execute(
"""
CREATE TABLE IF NOT EXISTS User (
uid INTEGER PRIMARY KEY AUTOINCREMENT,
username TEXT NOT NULL,
password TEXT NOT NULL
);
"""
)
conn.commit()
conn.close()