From 00fd0e0c0acf74f2339d39a53c19769b2a5e3999 Mon Sep 17 00:00:00 2001
From: Erik Reid <erik.reid@geant.org>
Date: Tue, 12 May 2020 11:56:07 +0200
Subject: [PATCH] added response caching

---
 inventory_provider/routes/poller.py | 29 +++++++++++++++++++----------
 1 file changed, 19 insertions(+), 10 deletions(-)

diff --git a/inventory_provider/routes/poller.py b/inventory_provider/routes/poller.py
index 52fcd5dc..bbc3b5d5 100644
--- a/inventory_provider/routes/poller.py
+++ b/inventory_provider/routes/poller.py
@@ -88,10 +88,9 @@ def poller_interface_oids(hostname):
 @common.require_accepts_json
 def service_category_interfaces(category):
 
-    def _interfaces():
-        r = common.get_current_redis()
-        for k in r.scan_iter(f'interface-services:{category.lower()}:*'):
-            cached_ifc = r.get(k.decode('utf-8')).decode('utf-8')
+    def _interfaces(rc, cat):
+        for k in rc.scan_iter(f'interface-services:{cat}:*'):
+            cached_ifc = rc.get(k.decode('utf-8')).decode('utf-8')
             cached_ifc = json.loads(cached_ifc)
             basic_ifc_info = dict()
             for k in ['description', 'interface', 'router']:
@@ -104,12 +103,22 @@ def service_category_interfaces(category):
                     ifc.update(basic_ifc_info)
                     yield ifc
 
-    result = list(_interfaces())
+    category = category.lower()
 
-    if not result:
-        return Response(
-            response=f'no info available for service category {category}',
-            status=404,
-            mimetype="text/html")
+    r = common.get_current_redis()
+    cache_key = f'classifier-cache:poller:service:{category}'
+    result = r.get(cache_key)
+
+    if result:
+        result = json.loads(result.decode('utf-8'))
+    else:
+        result = list(_interfaces(r, category))
+        if result:
+            r.set(cache_key, json.dumps(result).encode('utf-8'))
+        else:
+            return Response(
+                response=f'no info available for service category {category}',
+                status=404,
+                mimetype="text/html")
 
     return jsonify(result)
-- 
GitLab