import{_ as n,o as s,c as a,e}from"./app-gnbtOU7f.js";const t={},p=e(`

@shared_memory.passive_chan.on_receive(lambda d: d[0] == 'get')

func on_get()

源代码
@shared_memory.passive_chan.on_receive(lambda d: d[0] == 'get')
def on_get(data: tuple[str, dict[str, Any]]):
    key = data[1]['key']
    default = data[1]['default']
    recv_chan = data[1]['recv_chan']
    recv_chan.send(shared_memory.get(key, default))

@shared_memory.passive_chan.on_receive(lambda d: d[0] == 'set')

func on_set()

源代码
@shared_memory.passive_chan.on_receive(lambda d: d[0] == 'set')
def on_set(data: tuple[str, dict[str, Any]]):
    key = data[1]['key']
    value = data[1]['value']
    shared_memory.set(key, value)

@shared_memory.passive_chan.on_receive(lambda d: d[0] == 'delete')

func on_delete()

源代码
@shared_memory.passive_chan.on_receive(lambda d: d[0] == 'delete')
def on_delete(data: tuple[str, dict[str, Any]]):
    key = data[1]['key']
    shared_memory.delete(key)

@shared_memory.passive_chan.on_receive(lambda d: d[0] == 'get_all')

func on_get_all()

源代码
@shared_memory.passive_chan.on_receive(lambda d: d[0] == 'get_all')
def on_get_all(data: tuple[str, dict[str, Any]]):
    recv_chan = data[1]['recv_chan']
    recv_chan.send(shared_memory.get_all())

class KeyValueStore

method __init__(self)

源代码
def __init__(self):
    self._store = {}
    self.active_chan = Channel[tuple[str, Optional[dict[str, Any]]]](name='shared_memory-active')
    self.passive_chan = Channel[tuple[str, Optional[dict[str, Any]]]](name='shared_memory-passive')
    self.publish_channel = Channel[tuple[str, Any]](name='shared_memory-publish')
    self.is_main_receive_loop_running = False
    self.is_sub_receive_loop_running = False

method set(self, key: str, value: Any) -> None

说明: 设置键值对

参数:

源代码
def set(self, key: str, value: Any) -> None:
    """
        设置键值对
        Args:
            key: 键
            value: 值

        """
    if IS_MAIN_PROCESS:
        lock = _get_lock(key)
        with lock:
            self._store[key] = value
    else:
        self.passive_chan.send(('set', {'key': key, 'value': value}))

method get(self, key: str, default: Optional[Any] = None) -> Optional[Any]

说明: 获取键值对

参数:

返回: Any: 值

源代码
def get(self, key: str, default: Optional[Any]=None) -> Optional[Any]:
    """
        获取键值对
        Args:
            key: 键
            default: 默认值

        Returns:
            Any: 值
        """
    if IS_MAIN_PROCESS:
        lock = _get_lock(key)
        with lock:
            return self._store.get(key, default)
    else:
        recv_chan = Channel[Optional[Any]]('recv_chan')
        self.passive_chan.send(('get', {'key': key, 'default': default, 'recv_chan': recv_chan}))
        return recv_chan.receive()

method delete(self, key: str, ignore_key_error: bool = True) -> None

说明: 删除键值对

参数:

源代码
def delete(self, key: str, ignore_key_error: bool=True) -> None:
    """
        删除键值对
        Args:
            key: 键
            ignore_key_error: 是否忽略键不存在的错误

        Returns:
        """
    if IS_MAIN_PROCESS:
        lock = _get_lock(key)
        with lock:
            if key in self._store:
                try:
                    del self._store[key]
                    del _locks[key]
                except KeyError as e:
                    if not ignore_key_error:
                        raise e
    else:
        self.passive_chan.send(('delete', {'key': key}))

method get_all(self) -> dict[str, Any]

说明: 获取所有键值对

返回: dict[str, Any]: 键值对

源代码
def get_all(self) -> dict[str, Any]:
    """
        获取所有键值对
        Returns:
            dict[str, Any]: 键值对
        """
    if IS_MAIN_PROCESS:
        return self._store
    else:
        recv_chan = Channel[dict[str, Any]]('recv_chan')
        self.passive_chan.send(('get_all', {'recv_chan': recv_chan}))
        return recv_chan.receive()

method publish(self, channel_: str, data: Any) -> None

说明: 发布消息

参数:

源代码
def publish(self, channel_: str, data: Any) -> None:
    """
        发布消息
        Args:
            channel_: 频道
            data: 数据

        Returns:
        """
    self.active_chan.send(('publish', {'channel': channel_, 'data': data}))

method on_subscriber_receive(self, channel_: str) -> Callable[[ON_RECEIVE_FUNC], ON_RECEIVE_FUNC]

说明: 订阅者接收消息时的回调

参数:

返回: 装饰器

源代码
def on_subscriber_receive(self, channel_: str) -> Callable[[ON_RECEIVE_FUNC], ON_RECEIVE_FUNC]:
    """
        订阅者接收消息时的回调
        Args:
            channel_: 频道

        Returns:
            装饰器
        """
    if not IS_MAIN_PROCESS:
        raise RuntimeError('Cannot subscribe in sub process.')

    def decorator(func: ON_RECEIVE_FUNC) -> ON_RECEIVE_FUNC:

        async def wrapper(data: Any):
            if is_coroutine_callable(func):
                await func(data)
            else:
                func(data)
        if IS_MAIN_PROCESS:
            if channel_ not in _on_main_subscriber_receive_funcs:
                _on_main_subscriber_receive_funcs[channel_] = []
            _on_main_subscriber_receive_funcs[channel_].append(wrapper)
        else:
            if channel_ not in _on_sub_subscriber_receive_funcs:
                _on_sub_subscriber_receive_funcs[channel_] = []
            _on_sub_subscriber_receive_funcs[channel_].append(wrapper)
        return wrapper
    return decorator

@staticmethod

async method run_subscriber_receive_funcs(channel_: str, data: Any)

说明: 运行订阅者接收函数

参数:

源代码
@staticmethod
async def run_subscriber_receive_funcs(channel_: str, data: Any):
    """
        运行订阅者接收函数
        Args:
            channel_: 频道
            data: 数据
        """
    [asyncio.create_task(func(data)) for func in _on_main_subscriber_receive_funcs[channel_]]

async method start_receive_loop(self)

说明: 启动发布订阅接收器循环,在主进程中运行,若有子进程订阅则推送给子进程

源代码
async def start_receive_loop(self):
    """
        启动发布订阅接收器循环,在主进程中运行,若有子进程订阅则推送给子进程
        """
    if not IS_MAIN_PROCESS:
        raise RuntimeError('Cannot start receive loop in sub process.')
    while True:
        data = await self.active_chan.async_receive()
        if data[0] == 'publish':
            await self.run_subscriber_receive_funcs(data[1]['channel'], data[1]['data'])
            self.publish_channel.send(data)

class GlobalKeyValueStore

@classmethod

method get_instance(cls)

源代码
@classmethod
def get_instance(cls):
    if cls._instance is None:
        with cls._lock:
            if cls._instance is None:
                cls._instance = KeyValueStore()
    return cls._instance

var _on_main_subscriber_receive_funcs = {}

var _on_sub_subscriber_receive_funcs = {}

var shared_memory = GlobalKeyValueStore.get_instance()

`,65),o=[p];function c(l,i){return s(),a("div",null,o)}const r=n(t,[["render",c],["__file","storage.html.vue"]]),d=JSON.parse(`{"path":"/dev/api/comm/storage.html","title":"liteyuki.comm.storage","lang":"zh-CN","frontmatter":{"title":"liteyuki.comm.storage","description":"@shared_memory.passive_chan.on_receive(lambda d: d[0] == 'get') func on_get() 源代码 @shared_memory.passive_chan.on_receive(lambda d: d[0] == 'set') func on_set() 源代码 @shared_memor...","head":[["link",{"rel":"alternate","hreflang":"en-us","href":"https://vuepress-theme-hope-docs-demo.netlify.app/en/dev/api/comm/storage.html"}],["meta",{"property":"og:url","content":"https://vuepress-theme-hope-docs-demo.netlify.app/dev/api/comm/storage.html"}],["meta",{"property":"og:site_name","content":"LiteyukiBot 轻雪机器人"}],["meta",{"property":"og:title","content":"liteyuki.comm.storage"}],["meta",{"property":"og:description","content":"@shared_memory.passive_chan.on_receive(lambda d: d[0] == 'get') func on_get() 源代码 @shared_memory.passive_chan.on_receive(lambda d: d[0] == 'set') func on_set() 源代码 @shared_memor..."}],["meta",{"property":"og:type","content":"article"}],["meta",{"property":"og:locale","content":"zh-CN"}],["meta",{"property":"og:locale:alternate","content":"en-US"}],["meta",{"property":"og:updated_time","content":"2024-08-29T06:19:39.000Z"}],["meta",{"property":"article:modified_time","content":"2024-08-29T06:19:39.000Z"}],["script",{"type":"application/ld+json"},"{\\"@context\\":\\"https://schema.org\\",\\"@type\\":\\"Article\\",\\"headline\\":\\"liteyuki.comm.storage\\",\\"image\\":[\\"\\"],\\"dateModified\\":\\"2024-08-29T06:19:39.000Z\\",\\"author\\":[]}"]]},"headers":[{"level":3,"title":"@shared_memory.passive_chan.on_receive(lambda d: d[0] == 'get')","slug":"shared-memory-passive-chan-on-receive-lambda-d-d-0-get","link":"#shared-memory-passive-chan-on-receive-lambda-d-d-0-get","children":[]},{"level":3,"title":"func on_get()","slug":"func-on-get","link":"#func-on-get","children":[]},{"level":3,"title":"@shared_memory.passive_chan.on_receive(lambda d: d[0] == 'set')","slug":"shared-memory-passive-chan-on-receive-lambda-d-d-0-set","link":"#shared-memory-passive-chan-on-receive-lambda-d-d-0-set","children":[]},{"level":3,"title":"func on_set()","slug":"func-on-set","link":"#func-on-set","children":[]},{"level":3,"title":"@shared_memory.passive_chan.on_receive(lambda d: d[0] == 'delete')","slug":"shared-memory-passive-chan-on-receive-lambda-d-d-0-delete","link":"#shared-memory-passive-chan-on-receive-lambda-d-d-0-delete","children":[]},{"level":3,"title":"func on_delete()","slug":"func-on-delete","link":"#func-on-delete","children":[]},{"level":3,"title":"@shared_memory.passive_chan.on_receive(lambda d: d[0] == 'get_all')","slug":"shared-memory-passive-chan-on-receive-lambda-d-d-0-get-all","link":"#shared-memory-passive-chan-on-receive-lambda-d-d-0-get-all","children":[]},{"level":3,"title":"func on_get_all()","slug":"func-on-get-all","link":"#func-on-get-all","children":[]},{"level":3,"title":"class KeyValueStore","slug":"class-keyvaluestore","link":"#class-keyvaluestore","children":[]},{"level":3,"title":"method __init__(self)","slug":"method-init-self","link":"#method-init-self","children":[]},{"level":3,"title":"method set(self, key: str, value: Any) -> None","slug":"method-set-self-key-str-value-any-none","link":"#method-set-self-key-str-value-any-none","children":[]},{"level":3,"title":"method get(self, key: str, default: Optional[Any] = None) -> Optional[Any]","slug":"method-get-self-key-str-default-optional-any-none-optional-any","link":"#method-get-self-key-str-default-optional-any-none-optional-any","children":[]},{"level":3,"title":"method delete(self, key: str, ignore_key_error: bool = True) -> None","slug":"method-delete-self-key-str-ignore-key-error-bool-true-none","link":"#method-delete-self-key-str-ignore-key-error-bool-true-none","children":[]},{"level":3,"title":"method get_all(self) -> dict[str, Any]","slug":"method-get-all-self-dict-str-any","link":"#method-get-all-self-dict-str-any","children":[]},{"level":3,"title":"method publish(self, channel_: str, data: Any) -> None","slug":"method-publish-self-channel-str-data-any-none","link":"#method-publish-self-channel-str-data-any-none","children":[]},{"level":3,"title":"method on_subscriber_receive(self, channel_: str) -> Callable[[ON_RECEIVE_FUNC], ON_RECEIVE_FUNC]","slug":"method-on-subscriber-receive-self-channel-str-callable-on-receive-func-on-receive-func","link":"#method-on-subscriber-receive-self-channel-str-callable-on-receive-func-on-receive-func","children":[]},{"level":3,"title":"@staticmethod","slug":"staticmethod","link":"#staticmethod","children":[]},{"level":3,"title":"async method run_subscriber_receive_funcs(channel_: str, data: Any)","slug":"async-method-run-subscriber-receive-funcs-channel-str-data-any","link":"#async-method-run-subscriber-receive-funcs-channel-str-data-any","children":[]},{"level":3,"title":"async method start_receive_loop(self)","slug":"async-method-start-receive-loop-self","link":"#async-method-start-receive-loop-self","children":[]},{"level":3,"title":"class GlobalKeyValueStore","slug":"class-globalkeyvaluestore","link":"#class-globalkeyvaluestore","children":[]},{"level":3,"title":"@classmethod","slug":"classmethod","link":"#classmethod","children":[]},{"level":3,"title":"method get_instance(cls)","slug":"method-get-instance-cls","link":"#method-get-instance-cls","children":[]},{"level":3,"title":"var _on_main_subscriber_receive_funcs = {}","slug":"var-on-main-subscriber-receive-funcs","link":"#var-on-main-subscriber-receive-funcs","children":[]},{"level":3,"title":"var _on_sub_subscriber_receive_funcs = {}","slug":"var-on-sub-subscriber-receive-funcs","link":"#var-on-sub-subscriber-receive-funcs","children":[]},{"level":3,"title":"var shared_memory = GlobalKeyValueStore.get_instance()","slug":"var-shared-memory-globalkeyvaluestore-get-instance","link":"#var-shared-memory-globalkeyvaluestore-get-instance","children":[]}],"git":{"createdTime":1724031826000,"updatedTime":1724912379000,"contributors":[{"name":"snowy","email":"snowykami@outlook.com","commits":6}]},"readingTime":{"minutes":3.34,"words":1003},"filePathRelative":"dev/api/comm/storage.md","localizedDate":"2024年8月19日","autoDesc":true}`);export{r as comp,d as data};