diff --git a/app/main.py b/app/main.py index 2bb4b69..079aec0 100644 --- a/app/main.py +++ b/app/main.py @@ -1,20 +1,29 @@ from fastapi import FastAPI, HTTPException from fastapi.responses import RedirectResponse +from contextlib import asynccontextmanager from pydantic import BaseModel from app.utils import generate_short_code from dotenv import load_dotenv import os import sqlite3 -from contextlib import asynccontextmanager +import logging +# Set up logging configuration +logging.basicConfig(level=logging.INFO, + format="%(asctime)s - %(levelname)s - %(message)s") +logger = logging.getLogger(__name__) + +# Database connection setup @asynccontextmanager async def lifespan(app: FastAPI): conn = sqlite3.connect('urls.db') conn.execute('''CREATE TABLE IF NOT EXISTS urls (id INTEGER PRIMARY KEY, short_code TEXT, original_url TEXT, clicks INTEGER)''') conn.commit() + logger.info("Database initialized or already exists.") yield conn.close() + logger.info("Database connection closed.") app = FastAPI(lifespan=lifespan) @@ -27,10 +36,12 @@ class URLRequest(BaseModel): @app.get("/") def home(): + logger.info("Home endpoint accessed.") return {"message": "URL Shortener API"} @app.post("/shorten") def shorten_url(request: URLRequest): + logger.info(f"Request received to shorten URL: {request.url}") short_code = generate_short_code() conn = get_db_connection() @@ -42,14 +53,18 @@ def shorten_url(request: URLRequest): conn.commit() conn.close() - return {"short_url": f"{os.getenv('BASE_URL', 'http://localhost:8000')}/{short_code}"} + short_url = f"{os.getenv('BASE_URL', 'http://localhost:8000')}/{short_code}" + logger.info(f"Shortened URL created: {short_url}") + return {"short_url": short_url} @app.get("/{short_code}") def redirect_to_url(short_code: str): + logger.info(f"Redirect request received for short_code: {short_code}") conn = get_db_connection() url_data = conn.execute("SELECT original_url, clicks FROM urls WHERE short_code = ?", (short_code,)).fetchone() if url_data is None: + logger.warning(f"Shortened URL for {short_code} not found.") raise HTTPException(status_code=404, detail="Shortened URL not found") original_url, clicks = url_data @@ -57,4 +72,5 @@ def redirect_to_url(short_code: str): conn.commit() conn.close() + logger.info(f"Redirecting to {original_url}. Total clicks: {clicks + 1}") return RedirectResponse(url=original_url) \ No newline at end of file diff --git a/app/test_main.py b/app/test_main.py index 887e6aa..637d1ca 100644 --- a/app/test_main.py +++ b/app/test_main.py @@ -1,12 +1,10 @@ from fastapi.testclient import TestClient -from app.main import app import sys import os -# Add the 'app' folder to the sys.path sys.path.insert(0, os.path.abspath(os.path.join(os.path.dirname(__file__), '..'))) -from app.main import app # Now this should work correctly +from app.main import app client = TestClient(app) diff --git a/urls.db b/urls.db index d2b6c00..b82e8df 100644 Binary files a/urls.db and b/urls.db differ