Commits

Berker Peksag  committed 734a8b3

Use per-page cache.

  • Participants
  • Parent commits bff81c3

Comments (0)

Files changed (3)

+# coding: utf-8
+
 from flask import Flask, request, render_template
 from flaskext.babel import Babel
 
-from settings import DEBUG, PORT
+from decorators import cached
+from errors import ImproperlyConfigured
+try:
+    from settings import DEBUG, PORT
+except ImportError:
+    msg = "Kurulum için lütfen README.md belgesini okuyun."
+    raise ImproperlyConfigured(msg)
 from utils import get_statuses
 
 DEFAULT_LOCALE = "tr"
 
 
 @app.route("/")
+@cached(timeout=60 * 60)
 def index():
     return render_template("index.html", statuses=get_statuses(),
                            locale=get_locale())

File decorators.py

+from functools import wraps
+
+from flask import request
+from werkzeug.contrib.cache import SimpleCache
+
+from settings import DEBUG
+
+cache = SimpleCache()
+
+
+def cached(timeout=5 * 60, key='view/%s'):
+    def decorator(f):
+        @wraps(f)
+        def decorated_function(*args, **kwargs):
+            if DEBUG:
+                return f(*args, **kwargs)
+            cache_key = key % request.path
+            rv = cache.get(cache_key)
+            if rv is not None:
+                return rv
+            rv = f(*args, **kwargs)
+            cache.set(cache_key, rv, timeout=timeout)
+            return rv
+        return decorated_function
+    return decorator
 import requests
 
 from requests_oauthlib import OAuth1
-from werkzeug.contrib.cache import SimpleCache
 
 from errors import ImproperlyConfigured
-try:
-    from settings import twitter
-except ImportError:
-    msg = "Kurulum için lütfen README.md belgesini okuyun."
-    raise ImproperlyConfigured(msg)
-
-cache = SimpleCache()
+from settings import twitter
 
 
 def get_statuses():
-    statuses = cache.get("statuses")
-    if statuses is not None:
-        return statuses
-
     params = ("screen_name={screen_name}&count=10&exclude_replies=true&"
               "include_entities=false&include_rts=false&trim_user=true")
     url_fmt = "{url}{resource}?{params}".format
         signature_type="auth_header",
     )
     response = requests.get(url, auth=auth)
-    cache.set("statuses", response.json(), timeout=60 * 60)
     return response.json()