From 60aab91c082308f81db2471cdb53486287fe68fb Mon Sep 17 00:00:00 2001 From: Gergely Polonkai Date: Tue, 3 Jul 2018 10:51:43 +0200 Subject: [PATCH] User settings --- calsocial/models.py | 69 +++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 69 insertions(+) diff --git a/calsocial/models.py b/calsocial/models.py index 2975732..820b439 100644 --- a/calsocial/models.py +++ b/calsocial/models.py @@ -21,6 +21,7 @@ from datetime import datetime from flask_security import UserMixin, RoleMixin from flask_sqlalchemy import SQLAlchemy +from sqlalchemy.orm.exc import NoResultFound db = SQLAlchemy() users_roles = db.Table( @@ -29,6 +30,40 @@ users_roles = db.Table( db.Column('role_id', db.Integer(), db.ForeignKey('roles.id'))) +class SettingsProxy: + """Proxy object to get settings for a user + """ + + def __init__(self, user): + self.user = user + + def __getitem__(self, key): + setting = UserSetting.query \ + .filter(UserSetting.user == self.user) \ + .filter(UserSetting.key == key) \ + .first() + + if setting is None: + return None + + return setting.value + + def __setitem__(self, key, value): + try: + setting = UserSetting.query \ + .filter(UserSetting.user == self.user) \ + .filter(UserSetting.key == key) \ + .one() + except NoResultFound: + setting = UserSetting(user=self.user, key=key) + + setting.value = str(value) + db.session.add(setting) + + def __repr__(self): + return f'' + + class User(db.Model, UserMixin): """Database model for users """ @@ -59,6 +94,19 @@ class User(db.Model, UserMixin): secondary=users_roles, backref=db.backref('users', lazy='dynamic')) + @property + def settings(self): + """Get a settings proxy for the user + """ + + proxy = getattr(self, '_settings', None) + + if proxy is None: + proxy = SettingsProxy(self) + setattr(self, '_settings', proxy) + + return proxy + def __repr__(self): return f'' @@ -133,3 +181,24 @@ class Event(db.Model): def __repr__(self): return f'' + + +class UserSetting(db.Model): + """Database model for user settings + """ + + __tablename__ = 'user_settings' + + #: The ID of the user this setting belongs to + user_id = db.Column(db.Integer(), db.ForeignKey('users.id'), primary_key=True) + + user = db.relationship('User') + + #: The settings key + key = db.Column(db.String(length=40), primary_key=True) + + #: The settings value + value = db.Column(db.UnicodeText()) + + def __repr__(self): + return f''