Files
mxpic_EDA/backend/database.py
T

43 lines
1.3 KiB
Python

# backend/database.py
import sqlite3
import os
from werkzeug.security import generate_password_hash
# Save the database in the backend folder
DB_FILE = os.path.abspath(os.path.join(os.path.dirname(__file__), "..", "database", "mxpic_data.db"))
def init_db():
conn = sqlite3.connect(DB_FILE)
cursor = conn.cursor()
# Create Users Table
cursor.execute('''
CREATE TABLE IF NOT EXISTS users (
id INTEGER PRIMARY KEY AUTOINCREMENT,
username TEXT UNIQUE NOT NULL,
password_hash TEXT NOT NULL
)
''')
# Insert a test user if the table is empty
cursor.execute("SELECT * FROM users WHERE username = 'admin'")
if not cursor.fetchone():
test_hash = generate_password_hash("123456")
cursor.execute("INSERT INTO users (username, password_hash) VALUES (?, ?)", ("admin", test_hash))
print("Test user created. Username: admin | Password: 123456")
conn.commit()
conn.close()
def get_user(username):
conn = sqlite3.connect(DB_FILE)
cursor = conn.cursor()
cursor.execute("SELECT id, username, password_hash FROM users WHERE username = ?", (username,))
user = cursor.fetchone()
conn.close()
return user
if __name__ == "__main__":
init_db()
print("Database initialized successfully.")