| Total Complexity | 9 |
| Total Lines | 38 |
| Duplicated Lines | 0 % |
| Changes | 0 | ||
| 1 | # -*- coding: utf-8 -*- |
||
| 2 | from __future__ import absolute_import, unicode_literals |
||
| 3 | import json |
||
| 4 | from school_api.session import SessionStorage |
||
| 5 | from school_api.utils import to_text |
||
| 6 | |||
| 7 | |||
| 8 | class RedisStorage(SessionStorage): |
||
| 9 | |||
| 10 | def __init__(self, redis): |
||
| 11 | for method_name in ('get', 'set', 'delete'): |
||
| 12 | assert hasattr(redis, method_name) |
||
| 13 | self.redis = redis |
||
| 14 | |||
| 15 | def key_name(self, key): |
||
| 16 | return 'school:{0}'.format(key) |
||
| 17 | |||
| 18 | def get(self, key, default=None): |
||
| 19 | key = self.key_name(key) |
||
| 20 | value = self.redis.get(key) |
||
| 21 | if value is None: |
||
| 22 | return default |
||
| 23 | return json.loads(to_text(value)) |
||
| 24 | |||
| 25 | def set(self, key, value, ttl=None): |
||
| 26 | if value is None: |
||
| 27 | return |
||
| 28 | key = self.key_name(key) |
||
| 29 | value = json.dumps(value) |
||
| 30 | self.redis.set(key, value, ex=ttl) |
||
| 31 | |||
| 32 | def delete(self, key): |
||
| 33 | key = self.key_name(key) |
||
| 34 | self.redis.delete(key) |
||
| 35 | |||
| 36 | def expires_time(self, key): |
||
| 37 | return self.redis.ttl(self.key_name(key)) |
||
| 38 |