From 8a7772917cc2c55344555b73636900b0c13cf99d Mon Sep 17 00:00:00 2001 From: Gergely Polonkai Date: Tue, 3 Jul 2018 12:06:22 +0200 Subject: [PATCH] Add the User.timezone property MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit It either queries the user’s `timezone` setting, uses the app’s default time zone (stored in the `DEFAULT_TIMEZONE` configuration key), or uses UTC as a final fallback. --- calsocial/config_dev.py | 4 +++- calsocial/models.py | 18 ++++++++++++++++++ 2 files changed, 21 insertions(+), 1 deletion(-) diff --git a/calsocial/config_dev.py b/calsocial/config_dev.py index 5cc4d10..65dd49e 100644 --- a/calsocial/config_dev.py +++ b/calsocial/config_dev.py @@ -1,11 +1,13 @@ """Configuration file for the development environment """ -DEBUG = True ENV = 'dev' #: If ``True``, registration on the site is enabled. REGISTRATION_ENABLED = True +#: The default time zone +DEFAULT_TIMEZONE = 'Europe/Budapest' +DEBUG = True SQLALCHEMY_DATABASE_URI = 'sqlite:///local.db' SQLALCHEMY_TRACK_MODIFICATIONS = False SECRET_KEY = 'ThisIsNotSoSecret' diff --git a/calsocial/models.py b/calsocial/models.py index 820b439..3445ec6 100644 --- a/calsocial/models.py +++ b/calsocial/models.py @@ -18,6 +18,7 @@ """ from datetime import datetime +from warnings import warn from flask_security import UserMixin, RoleMixin from flask_sqlalchemy import SQLAlchemy @@ -107,6 +108,23 @@ class User(db.Model, UserMixin): return proxy + @property + def timezone(self): + from flask import current_app + from pytz import timezone, UTC + from pytz.exceptions import UnknownTimeZoneError + + timezone_str = self.settings['timezone'] + + if not timezone_str: + timezone_str = current_app.settings.get('DEFAULT_TIMEZONE', 'UTC') + + try: + return timezone(timezone_str) + except pytz.exceptions.UnknownTimeZoneError: + warn(f'Timezone of {user} (or the default timezone) "{timezone_str}" is invalid') + return UTC + def __repr__(self): return f''