Add the timezone property to app

It will make it easier to get a default time zone.
This commit is contained in:
Gergely Polonkai 2018-07-08 22:28:29 +02:00
parent ba7c766316
commit 943021e152
2 changed files with 35 additions and 8 deletions

View File

@ -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():

View File

@ -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'<User {self.id}({self.username})>'