-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathmain.py
More file actions
79 lines (64 loc) · 2 KB
/
main.py
File metadata and controls
79 lines (64 loc) · 2 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
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
import secrets
import string
from dotenv import load_dotenv
from os import getenv
from pymongo import MongoClient
from fastapi import FastAPI
from pydantic import BaseModel
from fastapi.responses import RedirectResponse
class shortData(BaseModel):
url: str
app = FastAPI()
load_dotenv()
mongo_URI = getenv("MONGO_URI")
Client = MongoClient(mongo_URI)
db = Client["urlDB"]
coll = db["urls"]
def generate_token(length=10):
characters = string.ascii_letters + string.digits # A-Z, a-z, 0-9
token = "".join(secrets.choice(characters) for _ in range(length))
return token
@app.get("/")
def home():
return RedirectResponse(url="/docs")
@app.post("/short")
def short(data: shortData):
try:
url = data.url
try:
while True:
token = generate_token()
exists = coll.find_one({"token": token}, {"_id": 0})
if exists:
continue
else:
state = coll.insert_one({"url": url, "token": token})
if state.inserted_id:
return {
"status": 200,
"message": "recorded",
"url": f"http://localhost:8000/{token}",
}
break
except:
return {"status": 404, "message": "Mongo DB error"}
except:
return {"status": 404, "message": "API Endpoint error"}
return 0
@app.get("/{token}")
def redirect(token: str):
try:
if token.isalnum():
try:
state = coll.find_one({"token": token}, {"url": 1,"_id":0})
if state:
url = state["url"]
return RedirectResponse(url=url)
else:
return {"message": "DB Error"}
except:
return {"message": "DB Error"}
else:
return {"message": "invalid url"}
except:
return {"message": "invalid url"}