diff --git a/calsocial/__init__.py b/calsocial/__init__.py index b3b6409..2468a7a 100644 --- a/calsocial/__init__.py +++ b/calsocial/__init__.py @@ -80,6 +80,8 @@ class CalendarSocialApp(Flask): Flask.__init__(self, name) + self._timezone = None + config_name = os.environ.get('ENV', config or 'dev') self.config.from_pyfile(f'config_{config_name}.py', True) # Make sure we look up users both by their usernames and email addresses @@ -106,6 +108,32 @@ class CalendarSocialApp(Flask): self.route(*args, **kwargs)(attr) + @property + def timezone(self): + """The default time zone of the app + """ + + from warnings import warn + + from flask import has_app_context + from pytz import timezone, utc + from pytz.exceptions import UnknownTimeZoneError + + if not has_app_context(): + return utc + + if not self._timezone: + timezone_str = current_app.settings.get('DEFAULT_TIMEZONE', 'UTC') + + try: + self._timezone = timezone(timezone_str) + except UnknownTimeZoneError: + warn(f'Timezone of {self} (or the default timezone) "{timezone_str}" is invalid') + + self._timezone = utc + + return self._timezone + @staticmethod @route('/') def hello(): diff --git a/calsocial/models.py b/calsocial/models.py index 6717e11..e1f3be8 100644 --- a/calsocial/models.py +++ b/calsocial/models.py @@ -111,19 +111,18 @@ class User(db.Model, UserMixin): @property def timezone(self): from flask import current_app - from pytz import timezone, UTC + from pytz import timezone from pytz.exceptions import UnknownTimeZoneError timezone_str = self.settings['timezone'] - if not timezone_str: - timezone_str = current_app.settings.get('DEFAULT_TIMEZONE', 'UTC') + if timezone_str: + try: + return timezone(timezone_str) + except UnknownTimeZoneError: + warn(f'Timezone of {self} (or the default timezone) "{timezone_str}" is invalid') - try: - return timezone(timezone_str) - except pytz.exceptions.UnknownTimeZoneError: - warn(f'Timezone of {user} (or the default timezone) "{timezone_str}" is invalid') - return UTC + return current_app.timezone def __repr__(self): return f''