Spaces:
Paused
Paused
Update main.py
Browse files
main.py
CHANGED
|
@@ -1,106 +1,106 @@
|
|
| 1 |
-
import sqlite3
|
| 2 |
-
import random
|
| 3 |
-
import string
|
| 4 |
-
from typing import Optional
|
| 5 |
-
from contextlib import contextmanager
|
| 6 |
-
from fastapi import FastAPI, HTTPException, Request
|
| 7 |
-
from fastapi.responses import HTMLResponse, RedirectResponse
|
| 8 |
-
from fastapi.templating import Jinja2Templates
|
| 9 |
-
from fastapi.staticfiles import StaticFiles
|
| 10 |
-
from pydantic import BaseModel, HttpUrl
|
| 11 |
-
import validators
|
| 12 |
-
|
| 13 |
-
app = FastAPI()
|
| 14 |
-
templates = Jinja2Templates(directory="templates")
|
| 15 |
-
|
| 16 |
-
BASE_URL = "
|
| 17 |
-
DB_FILE = "shortener.db"
|
| 18 |
-
|
| 19 |
-
class URLRequest(BaseModel):
|
| 20 |
-
original_url: str
|
| 21 |
-
|
| 22 |
-
@contextmanager
|
| 23 |
-
def get_db_connection():
|
| 24 |
-
conn = sqlite3.connect(DB_FILE)
|
| 25 |
-
try:
|
| 26 |
-
yield conn
|
| 27 |
-
finally:
|
| 28 |
-
conn.close()
|
| 29 |
-
|
| 30 |
-
def init_db():
|
| 31 |
-
with get_db_connection() as conn:
|
| 32 |
-
cursor = conn.cursor()
|
| 33 |
-
cursor.execute('''CREATE TABLE IF NOT EXISTS links (
|
| 34 |
-
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
| 35 |
-
original_url TEXT NOT NULL,
|
| 36 |
-
short_code TEXT UNIQUE NOT NULL,
|
| 37 |
-
short_url TEXT UNIQUE NOT NULL,
|
| 38 |
-
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
|
| 39 |
-
)''')
|
| 40 |
-
conn.commit()
|
| 41 |
-
|
| 42 |
-
def generate_short_code(length: int = 6) -> str:
|
| 43 |
-
return ''.join(random.choices(string.ascii_letters + string.digits, k=length))
|
| 44 |
-
|
| 45 |
-
def store_link(original_url: str) -> str:
|
| 46 |
-
with get_db_connection() as conn:
|
| 47 |
-
cursor = conn.cursor()
|
| 48 |
-
|
| 49 |
-
# Check if URL already exists
|
| 50 |
-
cursor.execute("SELECT short_url FROM links WHERE original_url = ?", (original_url,))
|
| 51 |
-
existing = cursor.fetchone()
|
| 52 |
-
if existing:
|
| 53 |
-
return existing[0]
|
| 54 |
-
|
| 55 |
-
# Generate unique short code
|
| 56 |
-
while True:
|
| 57 |
-
short_code = generate_short_code()
|
| 58 |
-
short_url = f"{BASE_URL}/{short_code}"
|
| 59 |
-
cursor.execute("SELECT id FROM links WHERE short_code = ?", (short_code,))
|
| 60 |
-
if not cursor.fetchone():
|
| 61 |
-
break
|
| 62 |
-
|
| 63 |
-
# Store new shortened URL
|
| 64 |
-
cursor.execute(
|
| 65 |
-
"INSERT INTO links (original_url, short_code, short_url) VALUES (?, ?, ?)",
|
| 66 |
-
(original_url, short_code, short_url)
|
| 67 |
-
)
|
| 68 |
-
conn.commit()
|
| 69 |
-
return short_url
|
| 70 |
-
|
| 71 |
-
@app.get("/", response_class=HTMLResponse)
|
| 72 |
-
async def read_root(request: Request):
|
| 73 |
-
return templates.TemplateResponse("index.html", {"request": request})
|
| 74 |
-
|
| 75 |
-
@app.post("/shorten/")
|
| 76 |
-
async def shorten_url(url_request: URLRequest):
|
| 77 |
-
if not url_request.original_url:
|
| 78 |
-
raise HTTPException(status_code=400, detail="URL is required")
|
| 79 |
-
|
| 80 |
-
if not url_request.original_url.startswith(('http://', 'https://')):
|
| 81 |
-
raise HTTPException(status_code=400, detail="URL must start with http:// or https://")
|
| 82 |
-
|
| 83 |
-
try:
|
| 84 |
-
short_url = store_link(url_request.original_url)
|
| 85 |
-
return {"original_url": url_request.original_url, "shortened_url": short_url}
|
| 86 |
-
except Exception as e:
|
| 87 |
-
raise HTTPException(status_code=500, detail="Error creating shortened URL")
|
| 88 |
-
|
| 89 |
-
@app.get("/{short_code}")
|
| 90 |
-
async def redirect_to_url(short_code: str):
|
| 91 |
-
with get_db_connection() as conn:
|
| 92 |
-
cursor = conn.cursor()
|
| 93 |
-
cursor.execute("SELECT original_url FROM links WHERE short_code = ?", (short_code,))
|
| 94 |
-
result = cursor.fetchone()
|
| 95 |
-
|
| 96 |
-
if not result:
|
| 97 |
-
raise HTTPException(status_code=404, detail="Short URL not found")
|
| 98 |
-
|
| 99 |
-
return RedirectResponse(url=result[0])
|
| 100 |
-
|
| 101 |
-
# Initialize database on startup
|
| 102 |
-
init_db()
|
| 103 |
-
|
| 104 |
-
if __name__ == "__main__":
|
| 105 |
-
import uvicorn
|
| 106 |
uvicorn.run(app, host="0.0.0.0", port=7860)
|
|
|
|
| 1 |
+
import sqlite3
|
| 2 |
+
import random
|
| 3 |
+
import string
|
| 4 |
+
from typing import Optional
|
| 5 |
+
from contextlib import contextmanager
|
| 6 |
+
from fastapi import FastAPI, HTTPException, Request
|
| 7 |
+
from fastapi.responses import HTMLResponse, RedirectResponse
|
| 8 |
+
from fastapi.templating import Jinja2Templates
|
| 9 |
+
from fastapi.staticfiles import StaticFiles
|
| 10 |
+
from pydantic import BaseModel, HttpUrl
|
| 11 |
+
import validators
|
| 12 |
+
|
| 13 |
+
app = FastAPI()
|
| 14 |
+
templates = Jinja2Templates(directory="templates")
|
| 15 |
+
|
| 16 |
+
BASE_URL = "https://arevedudaa-shortner.hf.space/"
|
| 17 |
+
DB_FILE = "shortener.db"
|
| 18 |
+
|
| 19 |
+
class URLRequest(BaseModel):
|
| 20 |
+
original_url: str
|
| 21 |
+
|
| 22 |
+
@contextmanager
|
| 23 |
+
def get_db_connection():
|
| 24 |
+
conn = sqlite3.connect(DB_FILE)
|
| 25 |
+
try:
|
| 26 |
+
yield conn
|
| 27 |
+
finally:
|
| 28 |
+
conn.close()
|
| 29 |
+
|
| 30 |
+
def init_db():
|
| 31 |
+
with get_db_connection() as conn:
|
| 32 |
+
cursor = conn.cursor()
|
| 33 |
+
cursor.execute('''CREATE TABLE IF NOT EXISTS links (
|
| 34 |
+
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
| 35 |
+
original_url TEXT NOT NULL,
|
| 36 |
+
short_code TEXT UNIQUE NOT NULL,
|
| 37 |
+
short_url TEXT UNIQUE NOT NULL,
|
| 38 |
+
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
|
| 39 |
+
)''')
|
| 40 |
+
conn.commit()
|
| 41 |
+
|
| 42 |
+
def generate_short_code(length: int = 6) -> str:
|
| 43 |
+
return ''.join(random.choices(string.ascii_letters + string.digits, k=length))
|
| 44 |
+
|
| 45 |
+
def store_link(original_url: str) -> str:
|
| 46 |
+
with get_db_connection() as conn:
|
| 47 |
+
cursor = conn.cursor()
|
| 48 |
+
|
| 49 |
+
# Check if URL already exists
|
| 50 |
+
cursor.execute("SELECT short_url FROM links WHERE original_url = ?", (original_url,))
|
| 51 |
+
existing = cursor.fetchone()
|
| 52 |
+
if existing:
|
| 53 |
+
return existing[0]
|
| 54 |
+
|
| 55 |
+
# Generate unique short code
|
| 56 |
+
while True:
|
| 57 |
+
short_code = generate_short_code()
|
| 58 |
+
short_url = f"{BASE_URL}/{short_code}"
|
| 59 |
+
cursor.execute("SELECT id FROM links WHERE short_code = ?", (short_code,))
|
| 60 |
+
if not cursor.fetchone():
|
| 61 |
+
break
|
| 62 |
+
|
| 63 |
+
# Store new shortened URL
|
| 64 |
+
cursor.execute(
|
| 65 |
+
"INSERT INTO links (original_url, short_code, short_url) VALUES (?, ?, ?)",
|
| 66 |
+
(original_url, short_code, short_url)
|
| 67 |
+
)
|
| 68 |
+
conn.commit()
|
| 69 |
+
return short_url
|
| 70 |
+
|
| 71 |
+
@app.get("/", response_class=HTMLResponse)
|
| 72 |
+
async def read_root(request: Request):
|
| 73 |
+
return templates.TemplateResponse("index.html", {"request": request})
|
| 74 |
+
|
| 75 |
+
@app.post("/shorten/")
|
| 76 |
+
async def shorten_url(url_request: URLRequest):
|
| 77 |
+
if not url_request.original_url:
|
| 78 |
+
raise HTTPException(status_code=400, detail="URL is required")
|
| 79 |
+
|
| 80 |
+
if not url_request.original_url.startswith(('http://', 'https://')):
|
| 81 |
+
raise HTTPException(status_code=400, detail="URL must start with http:// or https://")
|
| 82 |
+
|
| 83 |
+
try:
|
| 84 |
+
short_url = store_link(url_request.original_url)
|
| 85 |
+
return {"original_url": url_request.original_url, "shortened_url": short_url}
|
| 86 |
+
except Exception as e:
|
| 87 |
+
raise HTTPException(status_code=500, detail="Error creating shortened URL")
|
| 88 |
+
|
| 89 |
+
@app.get("/{short_code}")
|
| 90 |
+
async def redirect_to_url(short_code: str):
|
| 91 |
+
with get_db_connection() as conn:
|
| 92 |
+
cursor = conn.cursor()
|
| 93 |
+
cursor.execute("SELECT original_url FROM links WHERE short_code = ?", (short_code,))
|
| 94 |
+
result = cursor.fetchone()
|
| 95 |
+
|
| 96 |
+
if not result:
|
| 97 |
+
raise HTTPException(status_code=404, detail="Short URL not found")
|
| 98 |
+
|
| 99 |
+
return RedirectResponse(url=result[0])
|
| 100 |
+
|
| 101 |
+
# Initialize database on startup
|
| 102 |
+
init_db()
|
| 103 |
+
|
| 104 |
+
if __name__ == "__main__":
|
| 105 |
+
import uvicorn
|
| 106 |
uvicorn.run(app, host="0.0.0.0", port=7860)
|