-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.py
71 lines (58 loc) · 1.88 KB
/
main.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
59
60
61
62
63
64
65
66
67
68
import time
from fastapi.responses import RedirectResponse
import validators
from config import get_settings
import crud
from database import SessionLocal
from error import raiseError
import models
import schemas
from fastapi import Depends, FastAPI, Request
from sqlalchemy.orm import Session
from database import engine
app = FastAPI()
models.Base.metadata.create_all(bind=engine)
def get_db():
db = SessionLocal()
try:
yield db
finally:
db.close()
@app.get("/")
def read_root():
return "Hello World , URL Shortener here"
@app.post("/url", response_model=schemas.URLInfo)
def create_url(url: schemas.BaseURL, db: Session = Depends(get_db)):
if not validators.url(url.original_url):
raiseError(statusCode=404, message="Invalid URL")
db_url = crud.create_db_url(db=db, url=url)
db_url.url = db_url.key
return db_url
@app.get("/{url_key}")
def forward_to_original_url(
url_key: str,
request: Request,
db: Session = Depends(get_db)
):
db_url = crud.get_if_key_exists(db, url_key)
if db_url:
print(int(time.time()), db_url.expiry , int(time.time()) > db_url.expiry)
if db_url.active and int(time.time()) < db_url.expiry:
crud.update_db_clicks(db, db_url)
return RedirectResponse(db_url.original_url)
else:
raiseError(statusCode=410 , message=f" URL {request.url} not active or expired")
else:
raiseError(statusCode=404,message=f" URL {request.url} not found")
@app.get("/admin/{url_key}", response_model=schemas.AdminInfo)
def forward_to_original_url(
url_key: str,
request: Request,
db: Session = Depends(get_db)
):
db_url = crud.get_if_key_exists(db, url_key)
if db_url:
db_url.url = db_url.key
return db_url
else:
raiseError(statusCode=404,message=f" URL {request.url} not found")