-
Notifications
You must be signed in to change notification settings - Fork 1
/
app.py
58 lines (50 loc) · 1.8 KB
/
app.py
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
from fastapi import FastAPI, Request, Form
from fastapi.responses import HTMLResponse
from fastapi.templating import Jinja2Templates
from utils import ALERTS_TEMPLATES, valid_url
import requests
app = FastAPI()
templates = Jinja2Templates(directory="templates/", autoescape=False)
@app.get("/", response_class=HTMLResponse)
def start_page(request: Request):
return templates.TemplateResponse("index.html", context={"request": request})
@app.post("/", response_class=HTMLResponse)
def unshorten(request: Request, url: str = Form("")):
if not valid_url(url):
return templates.TemplateResponse(
"index.html",
context={
"request": request,
"final_text": ALERTS_TEMPLATES["error"].format("Not a valid LINK"),
},
)
try:
session = requests.Session()
response = session.head(url, allow_redirects=True)
if response.status_code == 200:
link = response.url
return templates.TemplateResponse(
"index.html",
context={
"request": request,
"final_text": ALERTS_TEMPLATES["success"].format(link, link, link),
},
)
else:
return templates.TemplateResponse(
"index.html",
context={
"request": request,
"final_text": ALERTS_TEMPLATES["error"].format(
f"Status Code: {response.status_code}"
),
},
)
except Exception as e:
return templates.TemplateResponse(
"index.html",
context={
"request": request,
"final_text": ALERTS_TEMPLATES["error"].format(e),
},
)