-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathservice.py
More file actions
36 lines (27 loc) · 1.18 KB
/
Copy pathservice.py
File metadata and controls
36 lines (27 loc) · 1.18 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
import string
import random
from fastapi import HTTPException
class URLShortenerService:
def __init__(self, db):
self.db = db
self.collection = db.urls
self.base_url = "http://localhost:8000/urls"
characters = string.ascii_letters + string.digits
async def get_shortened_url(self, original_url: str) -> str:
short_code = self.generate_short_code()
while await self.collection.find_one({"short_code": short_code}):
short_code = self.generate_short_code()
await self.save_to_database(short_code, original_url)
return self.base_url+"/"+short_code
def generate_short_code(self):
return ''.join(random.choices(self.characters, k=6))
async def save_to_database(self, short_code: str, original_url: str):
await self.collection.insert_one({
"original_url": original_url,
"short_code": short_code
})
async def get_original_url(self, short_code: str) -> str:
entry = await self.collection.find_one({"short_code": short_code})
if not entry:
raise HTTPException(status_code=404, detail="Short URL not found")
return entry["original_url"]