Run: black and isort

This commit is contained in:
2025-10-05 02:28:47 +02:00
parent bd3e23da07
commit 6e9f8a0589
12 changed files with 222 additions and 189 deletions

View File

@@ -1,5 +1,6 @@
import logging
from typing import Dict, Any
from typing import Any, Dict
from .interface import DatabaseInterface
from .sqlite_db import SQLiteDatabase
@@ -11,18 +12,18 @@ class DatabaseFactory:
@staticmethod
def create_database(db_type: str, config: Dict[str, Any]) -> DatabaseInterface:
if db_type.lower() == 'sqlite':
if 'path' not in config:
if db_type.lower() == "sqlite":
if "path" not in config:
raise ValueError("SQLite configuration requires 'path'")
return SQLiteDatabase(config['path'])
return SQLiteDatabase(config["path"])
elif db_type.lower() == 'mysql':
elif db_type.lower() == "mysql":
# Für später: MySQL-Implementierung
# from .mysql_db import MySQLDatabase
# return MySQLDatabase(config)
raise NotImplementedError("MySQL support not yet implemented")
elif db_type.lower() == 'postgresql':
elif db_type.lower() == "postgresql":
# Für später: PostgreSQL-Implementierung
# from .postgresql_db import PostgreSQLDatabase
# return PostgreSQLDatabase(config)

View File

@@ -1,5 +1,7 @@
import logging
from flask import g, current_app
from flask import current_app, g
from .interface import DatabaseInterface
logger = logging.getLogger(__name__)
@@ -16,7 +18,7 @@ class FlaskDatabaseManager:
Holt die Datenbank-Instanz für den aktuellen Request
Verwendet Flask's 'g' object für request-lokale Speicherung
"""
if 'database' not in g:
if "database" not in g:
g.database = self.database_factory_func()
g.database.connect()
g.database.create_user_table()
@@ -28,11 +30,11 @@ class FlaskDatabaseManager:
"""
Schließt die Datenbank-Verbindung am Ende des Requests
"""
database = g.pop('database', None)
database = g.pop("database", None)
if database is not None:
database.disconnect()
logger.debug("Database connection closed for request")
def init_app(self, app):
"""Registriert die Database-Manager-Funktionen bei Flask"""
app.teardown_appcontext(self.close_db)
app.teardown_appcontext(self.close_db)

View File

@@ -1,5 +1,5 @@
from abc import ABC, abstractmethod
from typing import Optional, List, Dict, Any
from typing import Any, Dict, List, Optional
class DatabaseInterface(ABC):

View File

@@ -1,7 +1,8 @@
import sqlite3
import logging
import sqlite3
from threading import local
from typing import Optional, Dict, Any
from typing import Any, Dict, Optional
from .interface import DatabaseInterface
logger = logging.getLogger(__name__)
@@ -17,12 +18,12 @@ class SQLiteDatabase(DatabaseInterface):
def _get_connection(self) -> sqlite3.Connection:
"""Holt oder erstellt eine thread-lokale Verbindung"""
if not hasattr(self._local, 'connection') or self._local.connection is None:
if not hasattr(self._local, "connection") or self._local.connection is None:
self._local.connection = sqlite3.connect(
self.db_path,
check_same_thread=False, # Erlaubt thread-übergreifende Nutzung
timeout=30.0,
detect_types=sqlite3.PARSE_DECLTYPES | sqlite3.PARSE_COLNAMES
detect_types=sqlite3.PARSE_DECLTYPES | sqlite3.PARSE_COLNAMES,
)
self._local.connection.row_factory = sqlite3.Row
# Optimierungen für bessere Performance
@@ -45,7 +46,7 @@ class SQLiteDatabase(DatabaseInterface):
def disconnect(self) -> None:
"""Schließt die thread-lokale Verbindung"""
if hasattr(self._local, 'connection') and self._local.connection:
if hasattr(self._local, "connection") and self._local.connection:
try:
self._local.connection.close()
self._local.connection = None
@@ -58,7 +59,8 @@ class SQLiteDatabase(DatabaseInterface):
conn = self._get_connection()
cursor = conn.cursor()
try:
cursor.execute("""
cursor.execute(
"""
CREATE TABLE IF NOT EXISTS users
(
id INTEGER PRIMARY KEY AUTOINCREMENT,
@@ -66,7 +68,8 @@ class SQLiteDatabase(DatabaseInterface):
email TEXT NOT NULL UNIQUE,
password_hash TEXT NOT NULL,
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP, updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP )
""")
"""
)
conn.commit()
logger.info("User table created/verified")
except Exception as e:
@@ -82,7 +85,7 @@ class SQLiteDatabase(DatabaseInterface):
try:
cursor.execute(
"INSERT INTO users (username, email, password_hash) VALUES (?, ?, ?)",
(username, email, password_hash)
(username, email, password_hash),
)
conn.commit()
logger.info(f"User created successfully: {email}")
@@ -105,7 +108,7 @@ class SQLiteDatabase(DatabaseInterface):
try:
cursor.execute(
"SELECT id, username, email, password_hash, created_at FROM users WHERE email = ?",
(email,)
(email,),
)
row = cursor.fetchone()
return dict(row) if row else None
@@ -122,7 +125,7 @@ class SQLiteDatabase(DatabaseInterface):
try:
cursor.execute(
"SELECT id, username, email, password_hash, created_at FROM users WHERE username = ?",
(username,)
(username,),
)
row = cursor.fetchone()
return dict(row) if row else None
@@ -137,10 +140,7 @@ class SQLiteDatabase(DatabaseInterface):
conn = self._get_connection()
cursor = conn.cursor()
try:
cursor.execute(
"SELECT password_hash FROM users WHERE email = ?",
(email,)
)
cursor.execute("SELECT password_hash FROM users WHERE email = ?", (email,))
row = cursor.fetchone()
return row if row else None
except Exception as e:
@@ -156,7 +156,7 @@ class SQLiteDatabase(DatabaseInterface):
try:
cursor.execute(
"UPDATE users SET password_hash = ?, updated_at = CURRENT_TIMESTAMP WHERE email = ?",
(new_password_hash, email)
(new_password_hash, email),
)
conn.commit()
success = cursor.rowcount > 0
@@ -186,4 +186,4 @@ class SQLiteDatabase(DatabaseInterface):
conn.rollback()
raise
finally:
cursor.close()
cursor.close()