Add the User.timezone property

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.
This commit is contained in:
Gergely Polonkai 2018-07-03 12:06:22 +02:00
parent 60aab91c08
commit 8a7772917c
2 changed files with 21 additions and 1 deletions

View File

@ -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'

View File

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