forked from gergely/calendar-social
Add the AppState model
This allows setting application state during run time
This commit is contained in:
@@ -21,12 +21,14 @@ from datetime import datetime
|
||||
from enum import Enum
|
||||
from warnings import warn
|
||||
|
||||
from flask import current_app
|
||||
from flask_babelex import lazy_gettext
|
||||
from flask_security import UserMixin, RoleMixin
|
||||
from flask_sqlalchemy import SQLAlchemy
|
||||
from sqlalchemy.orm.exc import NoResultFound
|
||||
from sqlalchemy_utils.types.choice import ChoiceType
|
||||
|
||||
from .app_state import app_state_base
|
||||
from .cache import cache
|
||||
from .utils import force_locale
|
||||
|
||||
@@ -206,7 +208,6 @@ class User(db.Model, UserMixin):
|
||||
If the user didn’t set a time zone yet, the application default is used.
|
||||
"""
|
||||
|
||||
from flask import current_app
|
||||
from pytz import timezone
|
||||
from pytz.exceptions import UnknownTimeZoneError
|
||||
|
||||
@@ -789,3 +790,64 @@ class Response(db.Model): # pylint: disable=too-few-public-methods
|
||||
|
||||
#: The response itself
|
||||
response = db.Column(db.Enum(ResponseType), nullable=False)
|
||||
|
||||
|
||||
class AppState(app_state_base(db.Model)): # pylint: disable=too-few-public-methods
|
||||
"""Database model for application state values
|
||||
"""
|
||||
|
||||
__tablename__ = 'app_state'
|
||||
|
||||
#: The environment that set this key
|
||||
env = db.Column(db.String(length=40), nullable=False, primary_key=True)
|
||||
|
||||
#: The key
|
||||
key = db.Column(db.String(length=80), nullable=False, primary_key=True)
|
||||
|
||||
#: The value of the key
|
||||
value = db.Column(db.Unicode(length=200), nullable=True)
|
||||
|
||||
@classmethod
|
||||
def __get_state__(cls, key):
|
||||
try:
|
||||
record = cls.query \
|
||||
.filter(cls.env == current_app.env) \
|
||||
.filter(cls.key == key) \
|
||||
.one()
|
||||
except NoResultFound:
|
||||
return None
|
||||
|
||||
return record.value
|
||||
|
||||
@classmethod
|
||||
def __set_state__(cls, key, value):
|
||||
try:
|
||||
record = cls.query \
|
||||
.filter(cls.env == current_app.env) \
|
||||
.filter(cls.key == key) \
|
||||
.one()
|
||||
except NoResultFound:
|
||||
record = cls(env=current_app.env, key=key)
|
||||
|
||||
record.value = value
|
||||
db.session.add(record)
|
||||
db.session.commit()
|
||||
|
||||
@classmethod
|
||||
def __set_state_default__(cls, key, value):
|
||||
try:
|
||||
record = cls.query \
|
||||
.filter(cls.env == current_app.env) \
|
||||
.filter(cls.key == key) \
|
||||
.one()
|
||||
except NoResultFound:
|
||||
pass
|
||||
else:
|
||||
return
|
||||
|
||||
record = cls(env=current_app.env, key=key, value=value)
|
||||
db.session.add(record)
|
||||
db.session.commit()
|
||||
|
||||
def __repr__(self):
|
||||
return f'<AppState {self.env}:{self.key}="{self.value}"'
|
||||
|
Reference in New Issue
Block a user