From c6cf9ac795617b21f9a8c3dfd0f5d22165cf72f5 Mon Sep 17 00:00:00 2001 From: Yax Date: Sun, 9 Jul 2017 16:53:58 +0200 Subject: [PATCH] homemade caching function --- app/__init__.py | 16 ++++++++++++++++ app/controllers/api.py | 18 +++++++++++------- app/run.py | 1 + 3 files changed, 28 insertions(+), 7 deletions(-) diff --git a/app/__init__.py b/app/__init__.py index 20164f2..86d275c 100644 --- a/app/__init__.py +++ b/app/__init__.py @@ -1,3 +1,19 @@ +import time from sanic import Sanic app = Sanic() +cache = {} +cache_time = 0 + +def get_cached(key): + global cache + global cache_time + value = cache.get(key,None) + if (time.time() - cache_time) > 120: + cache = {} + cache_time = time.time() + return value + +def set_cached(key, value): + global cache + cache[key] = value diff --git a/app/controllers/api.py b/app/controllers/api.py index d7f4148..58bdea5 100644 --- a/app/controllers/api.py +++ b/app/controllers/api.py @@ -4,13 +4,13 @@ import logging import config from sanic import response -from aiocache import cached, SimpleMemoryCache -from aiocache.serializers import JsonSerializer from app import app from app.models.site import Site from app.models.comment import Comment from app.helpers.hashing import md5 from app.services import processor +from app import get_cached +from app import set_cached logger = logging.getLogger(__name__) @@ -45,17 +45,21 @@ def query_comments(request): return r -@cached(ttl=300, serializer=JsonSerializer()) async def get_cached_comments_count(request): try: token = request.args.get('token', '') url = request.args.get('url', '') - count = Comment.select(Comment).join(Site).where( - (Comment.url == url) & - (Comment.published.is_null(False)) & - (Site.token == token)).count() + key = '%s:%s' % (token, url) + count = get_cached(key) + if count is None: + count = Comment.select(Comment).join(Site).where( + (Comment.url == url) & + (Comment.published.is_null(False)) & + (Site.token == token)).count() + set_cached(key, count) r = {'count': count} except: + logger.exception("cache exception") r = {'count': 0} return r diff --git a/app/run.py b/app/run.py index 9402796..5c821a0 100644 --- a/app/run.py +++ b/app/run.py @@ -70,4 +70,5 @@ if __name__ == '__main__': app.run(host=config.HTTP_ADDRESS, port=config.HTTP_PORT, debug=config.DEBUG, + log_config=None, workers=config.HTTP_WORKERS)