use only one handler function with arguments
1 file changed, 6 insertions(+), 44 deletions(-)
changed files
M mycal.py → mycal.py
@@ -245,67 +245,29 @@ async def startup(): """ Startup tasks before the server begins serving requests """ - global next_update_seconds logging.basicConfig(level=logging.INFO) await update_calendar_cache() schedule_next_update() app.add_background_task(periodic_calendar_update) -@app.route(f'/busy/{str.lower(config.name)}.ics') -@app.route(f'/{str.lower(config.name)}.ics') -async def busy_periods(): +@app.route(f'/{str.lower(config.name)}.ics', defaults = {'key': 'busy_ical'}) +@app.route(f'/busy/{str.lower(config.name)}.ics', defaults = {'key': 'busy_ical'}) +@app.route(f'/events/{str.lower(config.name)}.ics', defaults = {'key': 'events_ical'}) +async def events(key): try: - # Get the calendar data with a lock async with cache_condition: - if calendar_cache['busy_ical']: - # Calculate age (time since last update) - age = 0 - if calendar_cache['last_updated']: - age = int((datetime.now(tz=utc) - calendar_cache['last_updated']).total_seconds()) - - # Set headers with age and cache control - headers = { + if calendar_cache[key]: + return calendar_cache[key], { "Content-Type": "text/calendar", - "Age": str(age), "Cache-Control": f"max-age={next_update_seconds}", "Last-Modified": calendar_cache['last_updated'].strftime("%a, %d %b %Y %H:%M:%S GMT") } - - return calendar_cache['busy_ical'], headers else: return "Calendar data not yet available. Please try again shortly.", 503 except Exception as e: logging.error(f"Error serving calendar: {str(e)}") logging.error(traceback.format_exc()) return f"Error processing calendar: {str(e)}", 500 - -@app.route(f'/events/{str.lower(config.name)}.ics') -async def events(): - try: - # Get the calendar data with a lock - async with cache_condition: - if calendar_cache['events_ical']: - - # Calculate age (time since last update) - age = 0 - if calendar_cache['last_updated']: - age = int((datetime.now(tz=utc) - calendar_cache['last_updated']).total_seconds()) - - # Set headers with age and cache control - headers = { - "Content-Type": "text/calendar", - "Age": str(age), - "Cache-Control": f"max-age={next_update_seconds}", - "Last-Modified": calendar_cache['last_updated'].strftime("%a, %d %b %Y %H:%M:%S GMT") - } - - return calendar_cache['events_ical'], headers - else: - return "Calendar events data not yet available. Please try again shortly.", 503 - except Exception as e: - logging.error(f"Error serving events calendar: {str(e)}") - logging.error(traceback.format_exc()) - return f"Error processing calendar events: {str(e)}", 500 if __name__ == '__main__': app.run(debug=True)