# Pastebin fWgRbwsb import json from datetime import datetime from urllib.parse import parse_qs ​ ​ def application(environ, start_response): with open("urls.json", "r") as file: urls = json.load(file) method = environ["REQUEST_METHOD"] if method == "GET": path = environ["PATH_INFO"] key = path.removeprefix("/") if not key or not (url_data := urls.get(key)): start_response("404 Not Found", [("Content-Type", "application/json")]) return [json.dumps({"error": f"URL alias '{key}' does not exist." if key else "URL alias not provided."}).encode()] start_response("301 Moved Permanently", [("Location", url_data["url"])]) return [b''] elif method == "POST": data = parse_qs(environ["wsgi.input"].readline().decode(), True) key, url = data.get("key", [None])[0], data.get("url", [None])[0] if not key or not url or key in urls: start_response("400 Bad Request", [("Content-Type", "application/json")]) return [json.dumps({"error": f"URL alias '{key}' already exists." if key and url else "Alias or URL not provided."}).encode()] urls[key] = url_data = dict(key=key, url=url, date=datetime.now().isoformat()) with open("urls.json", "w", encoding="utf-8") as file: json.dump(urls, file, indent=4, sort_keys=True) url_data["val"] = f'https://{environ["HTTP_HOST"]}/{key}' start_response("201 Created", [("Content-Type", "application/json")]) return [json.dumps(url_data).encode()]