|
63 | 63 | requests.packages.urllib3.disable_warnings(category = InsecureRequestWarning) |
64 | 64 |
|
65 | 65 | # For performance improvement and not overloading the server, especially helpful during Elasticsearch index/reindex |
66 | | -# We use the cache as long as it exists |
67 | | -# Only clear the expired one based on TTL setting passively upon lookup rather than the actual expiration time |
68 | | -# This approach takes advantage of the cache and also prevents from memory overflow |
69 | 66 | entity_cache = {} |
70 | 67 |
|
71 | 68 |
|
@@ -4009,20 +4006,18 @@ def query_target_entity(id, user_token): |
4009 | 4006 | current_datetime = datetime.now() |
4010 | 4007 | current_timestamp = int(round(current_datetime.timestamp())) |
4011 | 4008 |
|
4012 | | - # Use the cached data as long as it exists, no matter if it's expired or not |
4013 | | - # Otherwise make a fresh request and add to the cache pool |
4014 | | - # But we'll clear the expired cache based on TTL setting passively |
4015 | | - if id in entity_cache: |
4016 | | - entity_dict = entity_cache[id]['entity'] |
| 4009 | + # Check if the cached entity is found and still valid based on TTL upon request, delete if expired |
| 4010 | + if (id in entity_cache) and (current_timestamp > entity_cache[id]['created_timestamp'] + SchemaConstants.REQUEST_CACHE_TTL): |
| 4011 | + del entity_cache[id] |
4017 | 4012 |
|
4018 | | - # We can still return the cache entity even if it's expired. |
4019 | | - # Just need to clear the expired data from cache so the next lookup makes a new call and stores the new data to cache |
4020 | | - if current_timestamp <= entity_cache[id]['created_timestamp'] + SchemaConstants.REQUEST_CACHE_TTL: |
4021 | | - logger.info(f'Using the entity data of {id} from cache at time {current_datetime}') |
4022 | | - else: |
4023 | | - logger.info(f'Using the entity data of {id} from cache at time {current_datetime} then clear it based on TTL setting') |
| 4013 | + logger.info(f'Deleted the expired entity cache of {id} at time {current_datetime}') |
| 4014 | + |
| 4015 | + # Use the cached data if found and still valid |
| 4016 | + # Otherwise, make a fresh query and add to cache |
| 4017 | + if (id in entity_cache) and (current_timestamp <= entity_cache[id]['created_timestamp'] + SchemaConstants.REQUEST_CACHE_TTL): |
| 4018 | + entity_dict = entity_cache[id]['entity'] |
4024 | 4019 |
|
4025 | | - del entity_cache[id] |
| 4020 | + logger.info(f'Using the valid cache data of entity {id} at time {current_datetime}') |
4026 | 4021 | else: |
4027 | 4022 | logger.info(f'Cache not found or expired. Making a new query to retrieve {id} at time {current_datetime}') |
4028 | 4023 |
|
|
0 commit comments