From 92a8a4301f6917e01b8eb58072bb5ca5c2b1fdaa Mon Sep 17 00:00:00 2001 From: Bottersnike Date: Wed, 29 Dec 2021 01:18:06 +0000 Subject: [PATCH] Add sitemap --- docs.py | 50 ++++++++++++++++++++++++++++--------------- templates/sitemap.xml | 9 ++++++++ 2 files changed, 42 insertions(+), 17 deletions(-) create mode 100644 templates/sitemap.xml diff --git a/docs.py b/docs.py index 88be5df..de55efd 100644 --- a/docs.py +++ b/docs.py @@ -1,10 +1,14 @@ -from flask import Flask, send_from_directory, render_template -from livereload import Server -import xml_lexer - +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') @@ -99,20 +103,32 @@ for base, _, files in os.walk(TEMPLATES + "/" + PAGES_BASE): app.add_url_rule(route, route, handler) -# from flask import url_for -# def has_no_empty_params(rule): -# defaults = rule.defaults if rule.defaults is not None else () -# arguments = rule.arguments if rule.arguments is not None else () -# return len(defaults) >= len(arguments) -# @app.route("/site-map") -# def site_map(): -# links = [] -# for rule in app.url_map.iter_rules(): -# if "GET" in rule.methods and has_no_empty_params(rule): -# url = url_for(rule.endpoint, **(rule.defaults or {})) -# links.append((url, rule.endpoint)) -# return str(links) +from flask import url_for +@app.route("/sitemap.xml") +def sitemap(): + host_components = urlparse(request.host_url) + host_base = host_components.scheme + "://" + host_components.netloc + 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)) + response.headers["Content-Type"] = "application/xml" + return response if __name__ == '__main__': app.config['TEMPLATES_AUTO_RELOAD'] = True diff --git a/templates/sitemap.xml b/templates/sitemap.xml new file mode 100644 index 0000000..24440ac --- /dev/null +++ b/templates/sitemap.xml @@ -0,0 +1,9 @@ + + +{% for url in urls %} + + {{ url[0] }}{% if url[1] %} + {{ url[1] }}{% endif %} + +{% endfor %} + \ No newline at end of file