add cache and function to cache urls requests
authorrougeronj
Wed, 18 Mar 2015 16:13:32 +0100
changeset 15 a3b7c0823378
parent 14 4d27fbc3f9df
child 16 f0f0f29395d5
add cache and function to cache urls requests
server/ammico/utils.py
server/settings.py
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/server/ammico/utils.py	Wed Mar 18 16:13:32 2015 +0100
@@ -0,0 +1,20 @@
+from django.core.cache import cache
+import requests
+import json
+
+def fetchJson(url):
+    cached = cache.get(url)
+    content = ""
+    if not cached:
+        r = requests.get(url)
+        if(r.ok):
+            cache.set(url, r.content)
+            content = r.content
+        else:
+            # Write some proper error handling code here
+            print ("Error - status code: " + r.status_code)  
+    else:
+        # Return the cached content
+        content = cached
+
+    return json.loads(content.decode('utf-8'))['VAL']
\ No newline at end of file
--- a/server/settings.py	Tue Mar 17 16:34:23 2015 +0100
+++ b/server/settings.py	Wed Mar 18 16:13:32 2015 +0100
@@ -79,6 +79,13 @@
     }
 }
 
+CACHES = {
+    'default': {
+        'BACKEND': 'django.core.cache.backends.db.DatabaseCache',
+        'LOCATION': 'cacheTable',
+    }
+}
+
 # Internationalization
 # https://docs.djangoproject.com/en/1.7/topics/i18n/