agenda/web_view.py

73 lines
1.7 KiB
Python
Raw Normal View History

2023-10-02 20:35:30 +01:00
#!/usr/bin/python3
"""Web page to show upcoming events."""
2023-10-21 07:16:21 +01:00
import functools
2023-10-06 23:29:22 +01:00
import inspect
import sys
import traceback
2023-10-21 07:16:21 +01:00
from datetime import date, datetime
2023-10-02 20:35:30 +01:00
2023-10-06 23:29:22 +01:00
import flask
import werkzeug
import werkzeug.debug.tbtools
2023-10-02 20:35:30 +01:00
from agenda import get_data
2023-10-06 23:29:22 +01:00
app = flask.Flask(__name__)
2023-10-02 20:35:30 +01:00
app.debug = True
2023-10-06 23:29:22 +01:00
@app.errorhandler(werkzeug.exceptions.InternalServerError)
def exception_handler(e: werkzeug.exceptions.InternalServerError) -> tuple[str, int]:
"""Handle exception."""
exec_type, exc_value, current_traceback = sys.exc_info()
assert exc_value
tb = werkzeug.debug.tbtools.DebugTraceback(exc_value)
summary = tb.render_traceback_html(include_title=False)
exc_lines = "".join(tb._te.format_exception_only())
last_frame = list(traceback.walk_tb(current_traceback))[-1][0]
last_frame_args = inspect.getargs(last_frame.f_code)
return (
flask.render_template(
"show_error.html",
plaintext=tb.render_traceback_text(),
exception=exc_lines,
exception_type=tb._te.exc_type.__name__,
summary=summary,
last_frame=last_frame,
last_frame_args=last_frame_args,
),
500,
)
2023-10-21 07:16:21 +01:00
def delta_days(today: date, when: date) -> str:
"""Return number of days from today as a string."""
delta = (when - today).days
match delta:
case 0:
return "today"
case 1:
return "1 day"
case _:
return f"{delta:,d} days"
2023-10-02 20:35:30 +01:00
@app.route("/")
def index() -> str:
"""Index page."""
now = datetime.now()
2023-10-06 22:23:34 +01:00
data = get_data(now)
2023-10-21 07:16:21 +01:00
days = functools.partial(delta_days, now.date())
2023-10-02 20:35:30 +01:00
2023-10-21 07:16:21 +01:00
return flask.render_template("index.html", days=days, **data)
2023-10-02 20:35:30 +01:00
if __name__ == "__main__":
app.run(host="0.0.0.0")