url-shortener/shortener.py

46 lines
1.2 KiB
Python
Raw Permalink 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-11-12 14:48:26 +00:00
if slug in urls["public"].keys():
return RedirectResponse(urls["public"][slug])
else:
return RedirectResponse("/")
2024-09-29 13:58:14 +00:00
if __name__ == "__main__":
import uvicorn
2024-11-12 14:50:51 +00:00
uvicorn.run(app, host="0.0.0.0", port=43599)