Switch to redis db for user registration

This commit is contained in:
2025-05-05 23:33:43 -05:00
parent 424a9d0fa8
commit 0856144417
8 changed files with 85 additions and 93 deletions

View File

@@ -1,22 +1,36 @@
import aiosqlite
from pathlib import Path
from src.config import DATABASE_FILENAME, DATA_PATH
from upstash_redis import Redis as UpstashRedis
from redis import Redis as LocalRedis, RedisError
from src.config import REDIS_URL, REDIS_TOKEN, USE_LOCAL_REDIS, LOCAL_REDIS_URL
from fastapi import HTTPException
import logging
async def get_db():
# Build the full database path
db_path = Path(DATA_PATH) / DATABASE_FILENAME
# Ensure the directory exists
db_path.parent.mkdir(parents=True, exist_ok=True)
async with aiosqlite.connect(db_path) as db:
# Enable WAL mode for better concurrency
await db.execute("PRAGMA journal_mode=WAL;")
await db.execute("""
CREATE TABLE IF NOT EXISTS users (
username TEXT PRIMARY KEY,
hashed_password TEXT
)
""")
await db.commit()
yield db
# Configure logging
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)
try:
if USE_LOCAL_REDIS:
redis = LocalRedis.from_url(LOCAL_REDIS_URL)
logger.info("Connecting to local Redis instance...")
else:
if not REDIS_URL or not REDIS_TOKEN:
raise ValueError("Upstash Redis configuration is missing. Please check your environment variables.")
redis = UpstashRedis(
url=REDIS_URL,
token=REDIS_TOKEN
)
logger.info("Connecting to Upstash Redis...")
# Test the connection
redis.ping()
logger.info("Successfully connected to Redis")
except ValueError as ve:
logger.error(f"Configuration error: {str(ve)}")
raise HTTPException(status_code=500, detail="Database configuration error")
except RedisError as re:
logger.error(f"Redis connection error: {str(re)}")
raise HTTPException(status_code=500, detail="Database connection error")
except Exception as e:
logger.error(f"Unexpected error while connecting to Redis: {str(e)}")
raise HTTPException(status_code=500, detail="Internal server error")