storage.py 1.7 KB
Newer Older
H
hjdhnx 已提交
1 2 3 4 5 6
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# File  : storage.py
# Author: DaShenHan&道长-----先苦后甜,任凭晚风拂柳颜------
# Date  : 2022/9/6

H
hjdhnx 已提交
7
from base.database import db
H
hjdhnx 已提交
8
from functools import lru_cache
H
hjdhnx 已提交
9
from utils.system import cfg
H
hjdhnx 已提交
10

H
hjdhnx 已提交
11 12
class Storage(db.Model):
    __tablename__ = 'storage'
H
hjdhnx 已提交
13

H
hjdhnx 已提交
14 15 16 17
    id = db.Column(db.Integer, primary_key=True, autoincrement=True)
    key = db.Column(db.String(20), unique=True)
    value = db.Column(db.UnicodeText())
    # value = db.Column(db.Text())
H
hjdhnx 已提交
18

H
hjdhnx 已提交
19 20 21
    def __repr__(self):
        return "<Storage(key='%s', value='%s')>" % (
            self.key, self.value)
H
hjdhnx 已提交
22

H
hjdhnx 已提交
23 24 25 26 27 28 29 30 31 32 33 34
    @classmethod
    def setItem(self, key, value=None):
        res = db.session.query(self).filter(self.key == key).first()
        if res:
            res.value = value
            db.session.add(res)
        else:
            res = Storage(key=key, value=value)
            db.session.add(res)
            db.session.flush()
        try:
            db.session.commit()
H
hjdhnx 已提交
35
            self.clearCache()
H
hjdhnx 已提交
36 37 38 39 40 41 42 43 44 45 46 47 48
            return res.id
        except Exception as e:
            print(f'发生了错误:{e}')
            return None

    @classmethod
    @lru_cache(maxsize=200)
    def getItem(self, key, value=''):
        res = db.session.query(self).filter(self.key == key).first()
        if res:
            return res.value or value
        else:
            return value
H
hjdhnx 已提交
49

H
hjdhnx 已提交
50 51 52 53 54 55 56 57 58 59 60
    @classmethod
    def clearItem(self, key):
        self.clearCache()
        res = db.session.query(self).filter(self.key == key).first()
        if res:
            res.delete()
            ret = db.session.commit()
            self.clearCache()
            return ret
        else:
            return True
H
hjdhnx 已提交
61

H
hjdhnx 已提交
62 63 64
    @classmethod
    def clearCache(self):
        self.getItem.cache_clear()