]> git.mxchange.org Git - fba.git/blob - fba/cache.py
Continued:
[fba.git] / fba / cache.py
1 # Fedi API Block - An aggregator for fetching blocking data from fediverse nodes
2 # Copyright (C) 2023 Free Software Foundation
3 #
4 # This program is free software: you can redistribute it and/or modify
5 # it under the terms of the GNU Affero General Public License as published
6 # by the Free Software Foundation, either version 3 of the License, or
7 # (at your option) any later version.
8 #
9 # This program is distributed in the hope that it will be useful,
10 # but WITHOUT ANY WARRANTY; without even the implied warranty of
11 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
12 # GNU Affero General Public License for more details.
13 #
14 # You should have received a copy of the GNU Affero General Public License
15 # along with this program.  If not, see <https://www.gnu.org/licenses/>.
16
17
18 # Cache for redundant SQL queries
19 cache = {}
20
21 ##### Cache #####
22
23 def is_cache_initialized(key: str) -> bool:
24     return key in cache
25
26 def set_all_cache_key(key: str, rows: list, value: any):
27     # NOISY-DEBUG: print(f"DEBUG: key='{key}',rows()={len(rows)},value[]={type(value)} - CALLED!")
28     if type(key) != str:
29         raise ValueError("Parameter key[]='{type(key)}' is not 'str'")
30     elif not is_cache_initialized(key):
31         # NOISY-DEBUG: print(f"DEBUG: Cache for key='{key}' not initialized.")
32         cache[key] = {}
33
34     for sub in rows:
35         # NOISY-DEBUG: print(f"DEBUG: Setting key='{key}',sub[{type(sub)}]='{sub}'")
36
37         if isinstance(sub, tuple):
38             cache[key][sub[0]] = value
39         else:
40             print(f"WARNING: Unsupported type row[]='{type(row)}'")
41
42     # NOISY-DEBUG: print("DEBUG: EXIT!")
43
44 def set_cache_key(key: str, sub: str, value: any):
45     if type(key) != str:
46         raise ValueError("Parameter key[]='{type(key)}' is not 'str'")
47     elif type(sub) != str:
48         raise ValueError("Parameter sub[]='{type(sub)}' is not 'str'")
49     elif not is_cache_initialized(key):
50         print(f"WARNING: Bad method call, key='{key}' is not initialized yet.")
51         raise Exception(f"Cache for key='{key}' is not initialized, but function called")
52
53     cache[key][sub] = value
54
55 def is_cache_key_set(key: str, sub: str) -> bool:
56     if type(key) != str:
57         raise ValueError("Parameter key[]='{type(key)}' is not 'str'")
58     elif type(sub) != str:
59         raise ValueError("Parameter sub[]='{type(sub)}' is not 'str'")
60     elif not is_cache_initialized(key):
61         print(f"WARNING: Bad method call, key='{key}' is not initialized yet.")
62         raise Exception(f"Cache for key='{key}' is not initialized, but function called")
63
64     return sub in cache[key]