@@ -29,21 +29,31 @@ def get_db_last_updated_at(session: Session):
2929 return result .timestamp () if result else 0
3030
3131
32+ type_mapping = {
33+ "str" : str ,
34+ "int" : int ,
35+ "float" : float ,
36+ "bool" : bool ,
37+ "dict" : dict ,
38+ "list" : list ,
39+ }
40+
41+
3242class SiteSettingProxy :
3343 __db_cache : dict = {}
3444 __last_updated_at_ts : float = 0
3545 __last_checked_at_ts : float = 0
3646 __mutex = threading .Lock ()
3747
38- def update_db_cache (self ):
48+ def update_db_cache (self , force_check = False ):
3949 with Session (engine ) as session :
4050 # Check if we need to update the cache every 10 seconds,
4151 # so it means settings will not be updated in real-time
4252 # which is acceptable for this project.
4353 # If we need real-time updates in the future, we can use
4454 # a message queue or a pub/sub system to notify the app.
4555 now = time .time ()
46- if now - self .__last_checked_at_ts > 10 :
56+ if force_check or ( now - self .__last_checked_at_ts > 10 ) :
4757 self .__last_checked_at_ts = now
4858 last_updated_at_ts = get_db_last_updated_at (session )
4959
@@ -89,8 +99,10 @@ def get_setting_group(self, group: str) -> dict[str, SettingValue]:
8999 )
90100 return result
91101
92- def get_all_settings (self ) -> dict [str , SettingValue ]:
93- self .update_db_cache ()
102+ def get_all_settings (
103+ self , force_check_db_cache : bool = False
104+ ) -> dict [str , SettingValue ]:
105+ self .update_db_cache (force_check_db_cache )
94106
95107 result = {}
96108 for _ , settings in default_settings .setting_groups .items ():
@@ -106,8 +118,31 @@ def get_all_settings(self) -> dict[str, SettingValue]:
106118 )
107119 return result
108120
121+ def setting_exists (self , name : str ) -> bool :
122+ return hasattr (default_settings , name )
123+
124+ def update_setting (self , session : Session , name : str , value : SettingType ):
125+ if not self .setting_exists (name ):
126+ raise AttributeError (f"Setting { name } does not exist." )
127+
128+ _default_setting : SettingValue = getattr (default_settings , name )
129+ if not isinstance (value , type_mapping [_default_setting .data_type ]):
130+ raise ValueError (f"{ name } must be of type `{ _default_setting .data_type } `." )
131+
132+ db_setting_obj = session .exec (
133+ select (DBSiteSetting ).filter (DBSiteSetting .name == name )
134+ ).first ()
135+ if db_setting_obj :
136+ db_setting_obj .value = value
137+ else :
138+ db_setting_obj = DBSiteSetting (
139+ name = name , value = value , data_type = _default_setting .data_type
140+ )
141+ session .add (db_setting_obj )
142+ session .commit ()
143+
109144
110145SiteSetting = SiteSettingProxy ()
111146
112147
113- __all__ = ["SiteSetting" , "SettingValue" ]
148+ __all__ = ["SiteSetting" , "SettingValue" , "SettingType" ]
0 commit comments