cleaner redis isolation

This commit is contained in:
codl 2017-09-24 16:43:54 +02:00
parent 520560ce79
commit b69f5db0dd
No known key found for this signature in database
GPG Key ID: 6CD7C8891ED1233A
2 changed files with 20 additions and 9 deletions

View File

@ -2,25 +2,31 @@ import brotli as brotli_
from flask import request, make_response
from threading import Thread
from hashlib import sha256
import redis
import redis as libredis
import os.path
import mimetypes
class BrotliCache(object):
def __init__(self, redis_uri='redis://', timeout=0.100, expire=60*60*6):
self.redis = redis.StrictRedis.from_url(redis_uri)
self._redis = None
self._redis_uri = redis_uri
self.timeout = timeout
self.expire = expire
@property
def redis(self):
if not self._redis:
self._redis = libredis.StrictRedis.from_url(self._redis_uri)
self._redis.client_setname('brotlicache')
return self._redis
def compress_and_cache(self, cache_key, lock_key, body, mode=brotli_.MODE_GENERIC):
self.redis.client_setname('brotlicache')
encbody = brotli_.compress(body, mode=mode)
self.redis.set(cache_key, encbody, px=int(self.expire*1000))
self.redis.delete(lock_key)
def wrap_response(self, response):
self.redis.client_setname('brotlicache')
if 'br' not in request.accept_encodings or response.is_streamed:
return response

View File

@ -1,6 +1,6 @@
import requests
import threading
import redis
import redis as libredis
from flask import make_response, abort
import secrets
import hmac
@ -12,19 +12,26 @@ import re
class ImgProxyCache(object):
def __init__(self, redis_uri='redis://', timeout=10, expire=60*60,
prefix='img_proxy', hmac_hash='sha1'):
self.redis = redis.StrictRedis.from_url(redis_uri)
self._redis = None
self._redis_uri = redis_uri
self.timeout = timeout
self.expire = expire
self.prefix = prefix
self.hash = hmac_hash
self.hmac_key = None
@property
def redis(self):
if not self._redis:
self._redis = libredis.StrictRedis.from_url(self._redis_uri)
self._redis.client_setname('img_proxy')
return self._redis
def key(self, *args):
return '{prefix}:1:{args}'.format(
prefix=self.prefix, args=":".join(args))
def token(self):
self.redis.client_setname('img_proxy')
if not self.hmac_key:
t = self.redis.get(self.key('hmac_key'))
if not t:
@ -54,7 +61,6 @@ class ImgProxyCache(object):
return url
def fetch_and_cache(self, url):
self.redis.client_setname('img_proxy')
resp = requests.get(url)
if(resp.status_code != 200):
return
@ -84,7 +90,6 @@ class ImgProxyCache(object):
resp.content, px=expire*1000)
def respond(self, identifier):
self.redis.client_setname('img_proxy')
url = self.url_for(identifier)
if not url:
return abort(403)