-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.py
36 lines (29 loc) · 864 Bytes
/
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
from fastapi import FastAPI, HTTPException
from fastapi.middleware.cors import CORSMiddleware
from fastapi.responses import RedirectResponse
from pydantic import BaseModel
import secrets
app = FastAPI()
class URLItem(BaseModel):
original_url: str
url_database = {}
origins = ["*"]
app.add_middleware(
CORSMiddleware,
allow_origins=origins,
allow_credentials=True,
allow_methods=["*"],
allow_headers=["*"],
)
@app.post("/shorten/")
def shorten_url(url_item: URLItem):
short_url = secrets.token_urlsafe(6)
url_database[short_url] = url_item.original_url
return {"short_url": short_url}
@app.get("/{short_url}")
def redirect_to_original(short_url: str):
original_url = url_database.get(short_url)
if original_url:
return RedirectResponse(url=original_url)
else:
return {"error": "URL not found"}