You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
DjangoBlog/servermanager/MemcacheStorage.py

48 lines
2.2 KiB

This file contains ambiguous Unicode characters!

This file contains ambiguous Unicode characters that may be confused with others in your current locale. If your use case is intentional and legitimate, you can safely ignore this warning. Use the Escape button to highlight these characters.

# 马莹:导入微信机器人(werobot)的会话存储基类,用于自定义会话存储方式
from werobot.session import SessionStorage
# 马莹导入微信机器人的JSON处理工具用于数据的序列化和反序列化
from werobot.utils import json_loads, json_dumps
# 马莹导入当前Django项目中djangoblog应用的缓存工具
from djangoblog.utils import cache
# 马莹定义基于Memcache的会话存储类继承自werobot的SessionStorage基类
class MemcacheStorage(SessionStorage):
# 马莹:初始化方法,设置缓存键的前缀,默认为'ws_'
def __init__(self, prefix='ws_'):
self.prefix = prefix # 马莹:存储缓存键的前缀
self.cache = cache # 马莹:引用导入的缓存工具实例
# 马莹:用于检查缓存存储是否可用的属性
@property
def is_available(self):
value = "1" # 马莹:定义测试值
# 马莹:尝试设置一个测试键值对到缓存中
self.set('checkavaliable', value=value)
# 马莹:通过比较设置的值和获取的值是否一致,判断缓存是否可用
return value == self.get('checkavaliable')
# 马莹:生成带前缀的缓存键名,避免键名冲突
def key_name(self, s):
return '{prefix}{s}'.format(prefix=self.prefix, s=s)
# 马莹从缓存中获取指定ID对应的会话数据
def get(self, id):
id = self.key_name(id) # 马莹:生成带前缀的缓存键
# 马莹从缓存中获取数据若不存在则返回空字典的JSON字符串
session_json = self.cache.get(id) or '{}'
# 马莹将JSON字符串反序列化为Python字典并返回
return json_loads(session_json)
# 马莹:将会话数据存入缓存
def set(self, id, value):
id = self.key_name(id) # 马莹:生成带前缀的缓存键
# 马莹将Python对象序列化为JSON字符串后存入缓存
self.cache.set(id, json_dumps(value))
# 马莹从缓存中删除指定ID的会话数据
def delete(self, id):
id = self.key_name(id) # 马莹:生成带前缀的缓存键
# 马莹:从缓存中删除该键对应的记录
self.cache.delete(id)