-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathshortner.py
More file actions
60 lines (45 loc) · 1.26 KB
/
shortner.py
File metadata and controls
60 lines (45 loc) · 1.26 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
import uuid
import os
import redis
from fastapi import FastAPI
from fastapi.middleware.cors import CORSMiddleware
from pydantic import BaseModel
from starlette.responses import RedirectResponse
# Start app and server
app = FastAPI()
# r = redis.Redis()
r = redis.from_url(os.environ.get("REDIS_URL"))
app.add_middleware(
CORSMiddleware,
allow_origins=["*"],
allow_credentials=True,
allow_methods=["*"],
allow_headers=["*"],
)
# Class to store url-name pair
class Item(BaseModel):
url: str
custom_target:str = None
# Test the root
@app.get("/")
def read_root():
return RedirectResponse(url="https://param211.github.io/link")
# Redirect
@app.get("/{short}")
def redirect_url(short: str):
for key in r.keys():
if r.get(key).decode("utf8") == short:
# return {"url": key.decode("utf8")}
return RedirectResponse(url=key.decode("utf8"))
return {"message": "URL does not exist"}
# Define POST
@app.post("/")
def shorten_url(item: Item):
url = item.url
if r.get(url) is None:
new_name = item.custom_target or str(uuid.uuid4())[-6:]
if r.mset({url: new_name}):
return {"short": r.get(url)}
else:
return {"message": "failed"}
return {"short": r.get(url)}