Reference
shared.caching.cache.AlanCache ¶
Two-layer caching system with local RAM and shared Redis backends.
This class implements a sophisticated caching mechanism that combines fast local RAM caching with persistent shared Redis caching. It automatically manages both layers and provides manual cache operations, decorators for function caching, and advanced features like async computation and cache warming.
The two-layer approach provides: - Ultra-fast local access for frequently used data - Shared persistence across application instances via Redis - Automatic fallback between layers - Configurable backend selection per use case
Attributes:
| Name | Type | Description |
|---|---|---|
disable_cache |
Global flag to disable all caching operations for testing. |
|
shared_cache |
Primary Redis cache backend for shared data. |
|
shared_cache_atomic |
Redis cache with atomic operations for race prevention. |
|
local_cache |
Fast in-memory cache for local data. |
|
local_cache_no_serializer |
Local cache without serialization for objects. |
Examples:
Basic cache operations:
>>> cache = AlanCache()
>>> cache.set("key", {"data": "value"}, timedelta(minutes=30))
>>> result = cache.get("key")
>>> cache.delete("key")
Check cache layers:
Note
- Automatically initializes from environment or app configuration
- Local cache is checked first for performance
- Redis cache provides persistence and cross-instance sharing
- Configuration via CACHE_TYPE, LOCALCACHE_TYPE environment variables
- Thread-safe for concurrent access
Source code in shared/caching/cache.py
clear_all_cache ¶
DANGER - Deletes all the cache
Source code in shared/caching/cache.py
clear_cached_func ¶
Deletes the specified functions cached values, based on given parameters
Source code in shared/caching/cache.py
clear_cached_func_all ¶
Deletes all the caches of the specified function (ignoring the parameters)
Source code in shared/caching/cache.py
clear_cached_func_some ¶
Deletes asynchronously some of the the specified function cached values, based on some of the given parameters, in local cache and shared (Redis) cache
Returns a tuple saying how many keys have been deleted so far on Redis, and if the process is finished or not.
WARNING 0: this function will only work if you used
cache_key_with_full_args option in the cache decorator that you
applied to the function
WARNING 1: this function deletes the keys asynchronously, if you need to wait until all cache keys are deleted you should interpret its return values and call it again.
WARNING 2: it doesn't support signatures with keyword-only arguments or positional-only arguments. Also it doesn't support omitting arguments in args or *wkargs
In the following signature, only the params b and c will be recognized, so clear_cached_func_some won't work properly:
def func(a, /, b, c, args, , d, **kwargs)
Source code in shared/caching/cache.py
delete ¶
Delete key from the cache.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
key
|
str
|
The key to delete. |
required |
Returns:
| Type | Description |
|---|---|
bool
|
Whether the key existed (in at least one cache layer) and has been deleted. |
Source code in shared/caching/cache.py
delete_from_funcname ¶
Deletes all the caches keys (local and Redis) for the given funcname.
Source code in shared/caching/cache.py
delete_many ¶
Deletes multiple keys at once.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
keys
|
str
|
The function accepts multiple keys as positional arguments. |
()
|
Returns:
| Type | Description |
|---|---|
list[str]
|
A list containing sucessfully deleted unique keys from any of the cache layers |
Source code in shared/caching/cache.py
get ¶
Look up key in the cache and return the value for it.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
key
|
str
|
The key to be looked up. |
required |
Returns:
| Type | Description |
|---|---|
Any
|
The value if it exists and is readable, else None. |
Source code in shared/caching/cache.py
get_many ¶
Returns a list of values for the given keys.
For each key an item in the list is created::
foo, bar = cache.get_many("foo", "bar")
Has the same error handling as :meth:get.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
keys
|
str
|
The function accepts multiple keys as positional arguments. |
()
|
Source code in shared/caching/cache.py
has ¶
Checks if a key exists in any of the cache layers, without returning it.
This is a cheap operation that bypasses loading the actual data on the backend.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
key
|
str
|
The key to check |
required |
Source code in shared/caching/cache.py
init_from_config_obj ¶
set ¶
Set a new key/value to the cache (overwrites value, if key already exists in the cache).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
key
|
str
|
The key to set |
required |
value
|
Any
|
The value for the key |
required |
expiration
|
timedelta
|
The cache expiration for the key (if not specified, it uses the default timeout). An expiration of 0 indicates that the cache never expires. |
required |
Source code in shared/caching/cache.py
shared.caching.cache.CACHED_FUNCS_TO_DELETE
module-attribute
¶
shared.caching.cache.CACHED_FUNCS_TO_REFRESH
module-attribute
¶
shared.caching.cache.CACHED_FUNCS_TO_REFRESH_LAST_RUN_FINISHED
module-attribute
¶
shared.caching.cache.CACHED_FUNC_KEYS_SET_ALPHA_SUFFIX
module-attribute
¶
shared.caching.cache.CACHED_FUNC_KEYS_SET_DEFAULT_NAME
module-attribute
¶
shared.caching.cache.CACHED_FUNC_KEYS_SET_PREFIX
module-attribute
¶
shared.caching.cache.CACHED_FUNC_KEYS_SET_SIZE_SUFFIX
module-attribute
¶
shared.caching.cache.DEFAULT_WARMUP_STARTUP_TIMEOUT
module-attribute
¶
shared.caching.cache.DELETION_CHECK_FREQUENCY_SECS
module-attribute
¶
shared.caching.cache.FLASK_CACHING_KEY_PREFIX
module-attribute
¶
shared.caching.cache.FuncnameFilterPairs
module-attribute
¶
shared.caching.cache.REFRESH_EVERY_GRANULARITY
module-attribute
¶
shared.caching.cache.cached ¶
cached(
*,
unless=None,
expire_in=None,
expire_when=None,
local_ram_cache_only=False,
shared_redis_cache_only=False,
cache_key_prefix="",
cache_key_with_request_path=False,
cache_key_with_query_string=False,
cache_key_with_func_args=True,
cache_key_with_full_args=False,
ignore_self=False,
ignore_cls=False,
args_to_ignore=None,
cache_none_values=False,
async_compute=False,
async_refresh_every=None,
warmup_on_startup=False,
on_cache_computed=None,
async_compute_job_timeout=None,
warmup_timeout=DEFAULT_WARMUP_STARTUP_TIMEOUT,
atomic_writes=False,
no_serialization=False
)
Decorator. Use this to cache the return value of a function.
See @cached_for for all the details.
Source code in shared/caching/cache.py
596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 | |
shared.caching.cache.cached_for ¶
Decorator for caching function results with time-based expiration.
This is a thin wrapper around @cached that provides a more intuitive interface for specifying cache expiration times. It supports both local RAM caching and shared Redis caching with extensive configuration options.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
weeks
|
int
|
Number of weeks until cache expiration. Defaults to 0. |
0
|
days
|
int
|
Number of days until cache expiration. Defaults to 0. |
0
|
hours
|
int
|
Number of hours until cache expiration. Defaults to 0. |
0
|
minutes
|
int
|
Number of minutes until cache expiration. Defaults to 0. |
0
|
seconds
|
int
|
Number of seconds until cache expiration. Defaults to 0. |
0
|
expire_when
|
Literal['object_is_destroyed'] | None
|
Conditional expiration trigger. Defaults to None. Options: - "object_is_destroyed": Cache expires when class instance is destroyed |
required |
unless
|
Callable[..., bool] | None
|
Callback that receives (func, args, *kwargs). If returns True, the value won't be cached. Defaults to None. |
required |
local_ram_cache_only
|
bool
|
If True, cache only in local RAM, not Redis. Defaults to False. |
required |
shared_redis_cache_only
|
bool
|
If True, cache only in Redis, not local RAM. Defaults to False. |
required |
no_serialization
|
bool | None
|
If True, store values as-is without serialization. Use with local_ram_cache_only=True for ORM objects. Defaults to False. |
required |
atomic_writes
|
Literal[False] | Literal['at_least_once'] | Literal['at_most_once']
|
Prevents race conditions. Defaults to False. Options: - False: No atomic writes (default) - "at_least_once": Function runs at least once, may run multiple times - "at_most_once": Function runs at most once across all processes |
required |
cache_key_prefix
|
str | Callable[..., str]
|
String or callback for custom cache key prefixes. If callback, receives (func, args, *kwargs) or no args. Defaults to "". |
required |
cache_key_with_request_path
|
bool
|
If True, include request path in cache key. Defaults to False. |
required |
cache_key_with_query_string
|
bool
|
If True, include query parameters in cache key. Defaults to False. |
required |
cache_key_with_func_args
|
bool
|
If True, include function arguments in cache key. Defaults to True. |
required |
cache_key_with_full_args
|
bool
|
If True, hash arguments separately. Required for using clear_cached_func_some for partial cache invalidation. Defaults to False. |
required |
args_to_ignore
|
list[str] | None
|
List of argument names to exclude from cache key when cache_key_with_func_args is True. Defaults to None. |
required |
ignore_self
|
bool
|
If True, ignore 'self' parameter in cache key (equivalent to adding 'self' to args_to_ignore). Defaults to False. |
required |
ignore_cls
|
bool
|
If True, ignore 'cls' parameter in cache key (equivalent to adding 'cls' to args_to_ignore). Defaults to False. |
required |
cache_none_values
|
bool
|
If True, cache None values. Incompatible with async_compute. Defaults to False. |
required |
async_compute
|
bool
|
If True, run function in background worker. Raises AsyncValueBeingBuiltException while computing. Defaults to False. |
required |
async_refresh_every
|
timedelta | None
|
Refresh cache periodically. Requires minimum 5 minutes, forces cache_key_with_request_path and cache_key_with_query_string to False. Defaults to None. |
required |
warmup_on_startup
|
bool
|
If True, pre-populate cache on application startup. Requires cache_key_with_request_path and cache_key_with_query_string to be False. Defaults to False. |
required |
on_cache_computed
|
Callable[[str, Any], Any] | None
|
Callback called after function execution with (cache_key, value). Should return modified value or None to prevent caching. Defaults to None. |
required |
async_compute_job_timeout
|
timedelta | None
|
Maximum time allowed for async cache computation. Defaults to None. |
required |
warmup_timeout
|
timedelta
|
Maximum time allowed for cache warmup. Defaults to 10 seconds. Long warmup times can slow application startup. |
required |
Returns:
| Name | Type | Description |
|---|---|---|
Callable |
Callable[[Callable[_P, _T]], Callable[_P, _T]]
|
A decorator that wraps the target function with caching behavior. |
Examples:
Basic time-based caching:
>>> @cached_for(minutes=30)
... def get_user_data(user_id: int):
... return fetch_user_from_database(user_id)
Local RAM caching only:
>>> @cached_for(minutes=5, local_ram_cache_only=True)
... def get_session_data(session_id: str):
... return fetch_session_data(session_id)
Async cache computation:
>>> @cached_for(hours=2, async_compute=True)
... def generate_report(report_id: int):
... return create_expensive_report(report_id)
Conditional caching:
>>> @cached_for(minutes=30, unless=lambda func, user_id, *args, **kwargs: user_id is None)
... def get_user_preferences(user_id: int | None):
... return fetch_preferences(user_id) if user_id else get_defaults()
Note
- Equivalent to @cached(expire_in=timedelta(...), **kwargs)
- The decorated function gains these attributes for introspection:
- make_cache_key: Function to generate cache keys
- uncached: Original function without caching
- expire_in: Cache expiration timedelta or None
- Async computation requires RQ workers running for CACHE_BUILDER_QUEUE
- Atomic writes only work with Redis backend, not local RAM cache
- Use cache_key_with_full_args=True for partial cache invalidation support
Source code in shared/caching/cache.py
54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 | |
shared.caching.cache.delete_shared_then_local_cache_funcnames_async ¶
Runs delete_shared_cache_funcname in async mode.
Returns a tuple saying how many keys have been deleted so far on Redis, and if the process is still running
Source code in shared/caching/cache.py
shared.caching.cache.delete_shared_then_local_cache_patterns ¶
Delete all keys in the Redis cache using CACHED_FUNC_KEYS sets for each funcname, then mark RAM caches to be deleted as well on all instances
Source code in shared/caching/cache.py
1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 | |
shared.caching.cache.memory_only_cache ¶
shared.caching.cache.request_cache_teardown_added
module-attribute
¶
shared.caching.cache.request_cached ¶
Decorator to cache at the request level, in RAM only, expires at the end of the request or 30s max.
It is a wrapper around @alan_cache.cached, with equivalent properties of: - expire_in=timedelta(seconds=30) - local_ram_cache_only=True - cache_key_with_func_args=True - cache_none_values=True
Additional args are passed to @alan_cache.cached, so see its doc for more info.
Note
WARNING: cache_key_prefix cannot be overriden
Source code in shared/caching/cache.py
1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 | |
shared.caching.cache.thread_local_class_cache ¶
Decorator to cache method results in thread-local storage.