url-shortener/main.py

39 lines
1,022 B
Python
Raw Normal View History

2024-09-29 13:37:39 +00:00
from typing import Annotated
from fastapi import FastAPI, Response, HTTPException, Form
2024-09-27 16:01:12 +00:00
from fastapi.responses import RedirectResponse, HTMLResponse
import json
2024-09-29 13:37:39 +00:00
2024-09-27 16:01:12 +00:00
app = FastAPI()
with open("urls.json", "r") as f:
urls = json.load(f)
@app.get("/")
async def root():
with open("index.html", "r") as file:
return HTMLResponse(file.read())
@app.get("/add/{slug}/{to}")
async def add(slug: str, to: str):
urls["public"][slug] = to
await _save()
return Response()
2024-09-29 13:37:39 +00:00
@app.post("/form")
async def form(slug: Annotated[str, Form()], link: Annotated[str, Form()]):
await add(slug=slug, to=link)
2024-09-27 16:01:12 +00:00
with open("submitted.html", "r") as file:
return HTMLResponse(file.read())
@app.get("/_save")
async def _save():
with open("urls.json", "w") as file:
json.dump(urls, file, indent=2, sort_keys=True)
2024-09-29 13:37:39 +00:00
@app.get("/{slug}")
2024-09-27 16:01:12 +00:00
async def slug_only(slug: str):
if slug == "favicon.ico":
return HTTPException(404)
else:
2024-09-29 13:37:39 +00:00
return RedirectResponse(urls["public"][slug])