-
Notifications
You must be signed in to change notification settings - Fork 5.3k
Expand file tree
/
Copy pathmain.py
More file actions
55 lines (38 loc) · 1.33 KB
/
main.py
File metadata and controls
55 lines (38 loc) · 1.33 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
import validators
from sqlalchemy.orm import Session
from fastapi import Depends, FastAPI, HTTPException, Request
from fastapi.responses import RedirectResponse
from . import crud, models, schemas
from .database import SessionLocal, engine
app = FastAPI()
models.Base.metadata.create_all(bind=engine)
def get_db():
db = SessionLocal()
try:
yield db
finally:
db.close()
def raise_bad_request(message):
raise HTTPException(status_code=400, detail=message)
def raise_not_found(request):
message = f"URL '{request.url}' doesn't exist"
raise HTTPException(status_code=404, detail=message)
@app.get("/")
def read_root():
return "Welcome to the URL shortener API :)"
@app.post("/url", response_model=schemas.URLInfo)
def create_url(url: schemas.URLBase, db: Session = Depends(get_db)):
if not validators.url(url.target_url):
raise_bad_request(message="Your provided URL is not valid")
db_url = crud.create_db_url(db=db, url=url)
db_url.url = db_url.key
db_url.admin_url = db_url.secret_key
return db_url
@app.get("/{url_key}")
def forward_to_target_url(
url_key: str, request: Request, db: Session = Depends(get_db)
):
if db_url := crud.get_db_url_by_key(db=db, url_key=url_key):
return RedirectResponse(db_url.target_url)
else:
raise_not_found(request)