User settings

This commit is contained in:
Gergely Polonkai 2018-07-03 10:51:43 +02:00
parent 3cf2c15d3d
commit 60aab91c08

View File

@ -21,6 +21,7 @@ from datetime import datetime
from flask_security import UserMixin, RoleMixin from flask_security import UserMixin, RoleMixin
from flask_sqlalchemy import SQLAlchemy from flask_sqlalchemy import SQLAlchemy
from sqlalchemy.orm.exc import NoResultFound
db = SQLAlchemy() db = SQLAlchemy()
users_roles = db.Table( users_roles = db.Table(
@ -29,6 +30,40 @@ users_roles = db.Table(
db.Column('role_id', db.Integer(), db.ForeignKey('roles.id'))) 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'<SettingsProxy for {self.user}>'
class User(db.Model, UserMixin): class User(db.Model, UserMixin):
"""Database model for users """Database model for users
""" """
@ -59,6 +94,19 @@ class User(db.Model, UserMixin):
secondary=users_roles, secondary=users_roles,
backref=db.backref('users', lazy='dynamic')) 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): def __repr__(self):
return f'<User {self.id}({self.username})>' return f'<User {self.id}({self.username})>'
@ -133,3 +181,24 @@ class Event(db.Model):
def __repr__(self): def __repr__(self):
return f'<Event {self.id} ({self.title}) of {self.user}>' return f'<Event {self.id} ({self.title}) of {self.user}>'
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'<UserSetting of {self.user}, {self.key}="{self.value}">'