Skip to content

Commit daeafea

Browse files
committed
Refactor views code to hopefully be slightly easier to deal with.
1 parent c03abc6 commit daeafea

17 files changed

+922
-839
lines changed

django_unicorn/utils.py

Lines changed: 32 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,16 +1,20 @@
11
import hmac
22
import logging
33
import pickle
4+
from typing import get_type_hints as typing_get_type_hints
45

56
from django.conf import settings
67

78
import shortuuid
9+
from cachetools.lru import LRUCache
810

911
from django_unicorn.errors import UnicornCacheError
1012

1113

1214
logger = logging.getLogger(__name__)
1315

16+
type_hints_cache = LRUCache(maxsize=100)
17+
1418

1519
def generate_checksum(data):
1620
"""
@@ -71,3 +75,31 @@ def get_cacheable_component(component):
7175
) from e
7276

7377
return component
78+
79+
80+
def get_type_hints(obj):
81+
"""
82+
Get type hints from an object. These get cached in a local memory cache for quicker look-up later.
83+
84+
Returns:
85+
An empty dictionary if no type hints can be retrieved.
86+
"""
87+
try:
88+
if obj in type_hints_cache:
89+
return type_hints_cache[obj]
90+
except TypeError:
91+
# Ignore issues with checking for an object in the cache, e.g. when a Django model is missing a PK
92+
pass
93+
94+
try:
95+
type_hints = typing_get_type_hints(obj)
96+
97+
# Cache the type hints just in case
98+
type_hints_cache[obj] = type_hints
99+
100+
return type_hints
101+
except TypeError:
102+
# Return an empty dictionary when there is a TypeError. From `get_type_hints`: "TypeError is
103+
# raised if the argument is not of a type that can contain annotations, and an empty dictionary
104+
# is returned if no annotations are present"
105+
return {}

0 commit comments

Comments
 (0)