Add support for setting user timezone

This commit is contained in:
Peter Stockings
2024-12-28 01:11:11 +11:00
parent 32f810a8b3
commit 2caddf52fe
9 changed files with 147 additions and 270 deletions

View File

@@ -4,6 +4,7 @@ from io import StringIO
import io
from flask import Blueprint, Response, make_response, render_template, redirect, request, send_file, url_for, flash
import humanize
from pytz import timezone, utc
from sqlalchemy import func
from werkzeug.security import generate_password_hash, check_password_hash
from werkzeug.http import http_date
@@ -177,10 +178,15 @@ def dashboard():
# Fetch readings
readings = readings_query.order_by(Reading.timestamp.desc()).all()
# Add relative timestamps to readings
# Fetch the user's timezone (default to 'UTC' if none is set)
user_timezone = current_user.profile.timezone if current_user.profile and current_user.profile.timezone else 'UTC'
local_tz = timezone(user_timezone)
# Add relative & local timestamps to readings
now = datetime.utcnow()
for reading in readings:
reading.relative_timestamp = humanize.naturaltime(now - reading.timestamp)
reading.local_timestamp = utc.localize(reading.timestamp).astimezone(local_tz)
# Calculate weekly summary and progress badges
systolic_avg, diastolic_avg, heart_rate_avg = calculate_weekly_summary(readings)
@@ -248,10 +254,20 @@ def edit_reading(reading_id):
if reading.user_id != current_user.id:
flash('You are not authorized to edit this reading.', 'danger')
return redirect(url_for('main.dashboard'))
# Fetch the user's timezone (default to 'UTC' if none is set)
user_timezone = current_user.profile.timezone if current_user.profile and current_user.profile.timezone else 'UTC'
local_tz = timezone(user_timezone)
reading.local_timestamp = utc.localize(reading.timestamp).astimezone(local_tz)
form = ReadingForm(obj=reading) # Populate form with existing reading data
form.timestamp.data = reading.local_timestamp
if form.validate_on_submit():
reading.timestamp = form.timestamp.data
# Convert the local timestamp back to UTC for saving
local_timestamp = form.timestamp.data
reading.timestamp = user_timezone.localize(local_timestamp).astimezone(utc)
reading.systolic = form.systolic.data
reading.diastolic = form.diastolic.data
reading.heart_rate = form.heart_rate.data
@@ -306,6 +322,7 @@ def profile():
profile.systolic_threshold = form.systolic_threshold.data or profile.systolic_threshold
profile.diastolic_threshold = form.diastolic_threshold.data or profile.diastolic_threshold
profile.dark_mode = form.dark_mode.data
profile.timezone = form.timezone.data
# Handle profile picture upload
if form.profile_pic.data: