|
@@ -1,36 +1,41 @@
|
|
|
import logging
|
|
|
import re
|
|
|
import sys
|
|
|
+from pathlib import Path
|
|
|
|
|
|
import requests
|
|
|
-from flask import Flask, redirect, render_template, request
|
|
|
+from fastapi import FastAPI, Request
|
|
|
+from fastapi.responses import HTMLResponse, RedirectResponse
|
|
|
+from fastapi.staticfiles import StaticFiles
|
|
|
+from fastapi.templating import Jinja2Templates
|
|
|
from requests import JSONDecodeError
|
|
|
from selectolax.parser import HTMLParser, Node
|
|
|
|
|
|
-app = Flask(__name__, template_folder="templates", static_folder="static")
|
|
|
+ROOT_PATH = Path(__file__).parent
|
|
|
+app = FastAPI(docs_url=None, redoc_url=None)
|
|
|
+app.mount("/static", StaticFiles(directory=ROOT_PATH / "static"), name="static")
|
|
|
+templates = Jinja2Templates(directory=ROOT_PATH / "templates")
|
|
|
|
|
|
|
|
|
def remove_classes(node: Node) -> Node:
|
|
|
"""Remove all classes from all nodes recursively."""
|
|
|
if "class" in node.attributes:
|
|
|
del node.attrs["class"]
|
|
|
-
|
|
|
for child in node.iter():
|
|
|
remove_classes(child)
|
|
|
return node
|
|
|
|
|
|
|
|
|
-@app.route("/", defaults={"path": ""})
|
|
|
-@app.route("/<path:path>")
|
|
|
-def root_route(path):
|
|
|
+@app.get("/{path:path}", response_class=HTMLResponse)
|
|
|
+async def catch_all(response: Request):
|
|
|
"""Check all routes on Urban Dictionary and redirect if needed."""
|
|
|
- path_without_host = re.sub(r"https?://[^/]+/", "", request.url)
|
|
|
+ path_without_host = re.sub(r"https?://[^/]+/+", "", str(response.url))
|
|
|
url = f"https://www.urbandictionary.com/{path_without_host}"
|
|
|
|
|
|
data = requests.get(url, timeout=10)
|
|
|
|
|
|
if data.history:
|
|
|
- return redirect(re.sub(r"https?://[^/]+", "", data.url), 302)
|
|
|
+ return RedirectResponse(re.sub(r"https?://[^/]+", "", data.url), status_code=301)
|
|
|
|
|
|
results = []
|
|
|
parser = HTMLParser(data.text)
|
|
@@ -62,13 +67,19 @@ def root_route(path):
|
|
|
pagination.attrs["class"] = "pagination"
|
|
|
pagination = pagination.html
|
|
|
|
|
|
- return render_template(
|
|
|
- "index.html", results=results, pagination=pagination, term=request.args.get("term")
|
|
|
+ return templates.TemplateResponse(
|
|
|
+ "index.html",
|
|
|
+ {
|
|
|
+ "request": response,
|
|
|
+ "results": results,
|
|
|
+ "pagination": pagination,
|
|
|
+ "term": response.query_params.get("term"),
|
|
|
+ },
|
|
|
)
|
|
|
|
|
|
|
|
|
if __name__ == "__main__":
|
|
|
- from waitress import serve
|
|
|
+ import uvicorn
|
|
|
|
|
|
logging.basicConfig(level=logging.INFO, stream=sys.stdout)
|
|
|
- serve(app, host="0.0.0.0", port=8080)
|
|
|
+ uvicorn.run(app, host="0.0.0.0", port=8080, access_log=False)
|