import datetime import re import os from urllib.parse import urlparse from flask import Flask, send_from_directory, render_template, make_response, request from livereload import Server import xml_lexer app = Flask(__name__) app.jinja_options.setdefault('extensions', []).append('jinja2_highlight.HighlightExtension') TEMPLATES = "templates" PAGES_BASE = "pages" STATIC = ["images"] ROOT = os.environ.get("EA_ROOT", "") def generate_xrpc_list(): output = "" @app.route("/styles.css") def styles(): return send_from_directory(".", "styles.css") @app.route("/tango.css") def tango(): return send_from_directory(".", "tango.css") for i in STATIC: for base, _, files in os.walk(i): for name in files: def handler(base, name): def handler(): return send_from_directory(base, name) return handler local_base = base.replace("\\", "/").strip(".").strip("/") route = local_base + "/" + name if not route.startswith("/"): route = "/" + route handler = handler(base, name) handler.__name__ == route app.add_url_rule(route, route, handler) for base, _, files in os.walk(TEMPLATES + "/" + PAGES_BASE): if ".git" in base: continue if base.startswith(TEMPLATES): base = base[len(TEMPLATES):] for name in files: if name.endswith(".html"): def handler(base, name): def handler(): return render_template( os.path.join(base, name).strip("/").replace("\\", "/"), ROOT=ROOT, generate_xrpc_list=generate_xrpc_list ) return handler local_base = base.replace("\\", "/").strip(".").strip("/") if local_base.startswith(PAGES_BASE): local_base = local_base[len(PAGES_BASE):] route = local_base + "/" + name if route.endswith("/index.html"): route = route[:-10] if not route.startswith("/"): route = "/" + route handler = handler(base, name) handler.__name__ == route app.add_url_rule(route, route, handler) from flask import url_for @app.route("/sitemap.xml") def sitemap(): host_components = urlparse(request.host_url) host_base = "https://bsnk.me" + ROOT links = [] for rule in app.url_map.iter_rules(): if "GET" in rule.methods and len(rule.arguments) == 0: url = url_for(rule.endpoint, **(rule.defaults or {})) if not url.endswith(("/", ".html", ".png")): continue path = rule.endpoint if path.endswith("/"): path += "index.html" path = os.path.join(TEMPLATES, PAGES_BASE, path.lstrip("/")) if os.path.exists(path): mod_time = os.path.getmtime(path) mod_time = datetime.datetime.fromtimestamp(mod_time).strftime("%Y-%m-%dT%H:%M:%SZ") else: mod_time = None links.append((host_base + url, mod_time)) response = make_response(render_template("sitemap.xml", urls=links[::-1])) response.headers["Content-Type"] = "application/xml" return response if __name__ == '__main__': app.config['TEMPLATES_AUTO_RELOAD'] = True app.config['DEBUG'] = True app.run(debug=True, port=3000, host="0.0.0.0") # server = Server(app.wsgi_app) # server.watch(".") # server.serve(port=3000)