MemoryStorage.delete()   A
last analyzed

Complexity

Conditions 1

Size

Total Lines 3
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 1
eloc 3
nop 2
dl 0
loc 3
rs 10
c 0
b 0
f 0
1
# -*- coding: utf-8 -*-
2
from __future__ import absolute_import, unicode_literals
3
import time
4
from school_api.session import SessionStorage
5
from school_api.utils import to_text
6
7
8
class MemoryStorage(SessionStorage):
9
    ''' 非持久化缓存 不推荐使用'''
10
11
    def __init__(self):
12
        self._data = {}
13
14
    def key_name(self, key):
15
        return 'school:{0}'.format(key)
16
17
    def get(self, key, default=None):
18
        key = self.key_name(key)
19
        value = None
20
        data = self._data.get(key, default)
21
        if data:
22
            if data['expires_at'] is True or data['expires_at'] > time.time():
23
                # 为True时:永不过期, 大于当前时间为:不到过期时间
24
                value = data['value']
25
            else:
26
                self.delete(key)
27
        return value
28
29
    def set(self, key, value, ttl=None):
30
31
        if value is None:
32
            return
33
34
        key = self.key_name(key)
35
        expires_at = not ttl or time.time() + ttl
36
        data = {'value': value, 'expires_at': expires_at}
37
        self._data[key] = data
38
39
    def delete(self, key):
40
        key = self.key_name(key)
41
        self._data.pop(key, None)
42
43
    def expires_time(self, key):
44
        data = self._data.get(self.key_name(key))
45
        return data['expires_at'] - time.time()
46