refactor: use contextlib.suppress and sort __slots__ in backends

This commit is contained in:
2026-02-04 01:07:32 +00:00
parent ac90ac4141
commit 3510ea564a
3 changed files with 23 additions and 20 deletions

View File

@@ -3,27 +3,30 @@
from __future__ import annotations
import asyncio
import contextlib
import json
import sqlite3
import time
from pathlib import Path
from typing import Any
from typing import TYPE_CHECKING, Any
from fastapi_traffic.backends.base import Backend
from fastapi_traffic.exceptions import BackendError
if TYPE_CHECKING:
from pathlib import Path
class SQLiteBackend(Backend):
"""SQLite-based backend with connection pooling and async support."""
__slots__ = (
"_db_path",
"_connection",
"_lock",
"_cleanup_interval",
"_cleanup_task",
"_pool_size",
"_connection",
"_connections",
"_db_path",
"_lock",
"_pool_size",
)
def __init__(
@@ -59,9 +62,7 @@ class SQLiteBackend(Backend):
"""Ensure a database connection exists."""
if self._connection is None:
loop = asyncio.get_event_loop()
self._connection = await loop.run_in_executor(
None, self._create_connection
)
self._connection = await loop.run_in_executor(None, self._create_connection)
assert self._connection is not None
return self._connection
@@ -87,16 +88,20 @@ class SQLiteBackend(Backend):
def _create_tables_sync(self, conn: sqlite3.Connection) -> None:
"""Synchronously create tables."""
conn.execute("""
conn.execute(
"""
CREATE TABLE IF NOT EXISTS rate_limits (
key TEXT PRIMARY KEY,
data TEXT NOT NULL,
expires_at REAL NOT NULL
)
""")
conn.execute("""
"""
)
conn.execute(
"""
CREATE INDEX IF NOT EXISTS idx_expires_at ON rate_limits(expires_at)
""")
"""
)
async def _cleanup_loop(self) -> None:
"""Background task to clean up expired entries."""
@@ -247,10 +252,8 @@ class SQLiteBackend(Backend):
"""Close the database connection."""
if self._cleanup_task is not None:
self._cleanup_task.cancel()
try:
with contextlib.suppress(asyncio.CancelledError):
await self._cleanup_task
except asyncio.CancelledError:
pass
self._cleanup_task = None
if self._connection is not None: