(type, amount, *keywords)
| 48 | queryCache = {} |
| 49 | |
| 50 | def cachedQuery(type, amount, *keywords): |
| 51 | itemCache[type] = localItemCache = weakref.WeakValueDictionary() |
| 52 | queryCache[type] = typeQueryCache = {} |
| 53 | |
| 54 | def deco(function): |
| 55 | localQueryCache = typeQueryCache[function] = {} |
| 56 | |
| 57 | def setCache(cacheKey, args, kwargs): |
| 58 | items = function(*args, **kwargs) |
| 59 | IDs = set() |
| 60 | localQueryCache[cacheKey] = (isinstance(items, list), IDs) |
| 61 | stuff = items if isinstance(items, list) else (items,) |
| 62 | for item in stuff: |
| 63 | ID = getattr(item, "ID", None) |
| 64 | if ID is None: |
| 65 | # Some uncachable data, don't cache this query |
| 66 | del localQueryCache[cacheKey] |
| 67 | break |
| 68 | localItemCache[ID] = item |
| 69 | IDs.add(ID) |
| 70 | |
| 71 | return items |
| 72 | |
| 73 | def checkAndReturn(*args, **kwargs): |
| 74 | useCache = kwargs.pop("useCache", True) |
| 75 | cacheKey = [] |
| 76 | items = None |
| 77 | cacheKey.extend(args) |
| 78 | for keyword in keywords: |
| 79 | cacheKey.append(kwargs.get(keyword)) |
| 80 | |
| 81 | cacheKey = tuple(cacheKey) |
| 82 | info = localQueryCache.get(cacheKey) |
| 83 | if info is None or not useCache: |
| 84 | items = setCache(cacheKey, args, kwargs) |
| 85 | else: |
| 86 | l, IDs = info |
| 87 | if l: |
| 88 | items = [] |
| 89 | for ID in IDs: |
| 90 | data = localItemCache.get(ID) |
| 91 | if data is None: |
| 92 | # Fuck, some of our stuff isn't cached it seems. |
| 93 | items = setCache(cacheKey, args, kwargs) |
| 94 | break |
| 95 | items.append(data) |
| 96 | else: |
| 97 | for ID in IDs: |
| 98 | items = localItemCache.get(ID) |
| 99 | if items is None: |
| 100 | items = setCache(cacheKey, args, kwargs) |
| 101 | break |
| 102 | |
| 103 | return items |
| 104 | |
| 105 | return checkAndReturn |
| 106 | |
| 107 | return deco |
nothing calls this directly
no outgoing calls
no test coverage detected