-
Notifications
You must be signed in to change notification settings - Fork 1
/
session.py
126 lines (97 loc) · 3.4 KB
/
session.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
# -*- coding: utf-8 -*-
from typing import (
Any,
Dict,
ItemsView,
KeysView,
Literal,
ValuesView,
Union,
MutableMapping,
)
from typing_extensions import TypeAlias
from loguru import logger
import datetime
Key: TypeAlias = Union[str, int]
class State(MutableMapping[Key, Any]):
"""Implement all methods of streamlit.SessionState
'clear', 'get', 'items', 'keys', 'pop', 'popitem',
'setdefault', 'to_dict', 'update', 'values'
"""
_instance = None
def __new__(cls, at: Literal["cli", "web"]):
if cls._instance is None:
cls._instance = super(State, cls).__new__(cls)
cls._instance._init_state(at)
return cls._instance
def _init_state(self, at: Literal["cli", "web"]):
self._session_id = datetime.datetime.now().strftime(
"%Y-%m-%d_%H-%M-%S",
)
logger.add(f"logs/{self._session_id}.log", rotation="10 MB")
if at == "cli":
self._state = {}
elif at == "web":
import streamlit as st
self._state = st.session_state
def __getitem__(self, key: Key) -> Any:
return self._state[key]
def __setitem__(self, key: Key, value: Any):
self._state[key] = value
logger.info(f"Set {key} = {value}")
def __delitem__(self, key: Key):
del self._state[key]
logger.info(f"Deleted {key}")
def __getattr__(self, key: Key) -> Any:
try:
return self._state[key]
except KeyError:
raise AttributeError(f"'State' object has no attribute '{key}'")
def __setattr__(self, key: str, value: Any):
if key in ["_state", "_session_id", "_at"]:
super().__setattr__(key, value)
else:
self._state[key] = value
logger.info(f"Set {key} = {value}")
def __delattr__(self, key: Key):
try:
del self._state[key]
logger.info(f"Deleted {key}")
except KeyError:
raise AttributeError(f"'State' object has no attribute '{key}'")
def __iter__(self):
return iter(self._state)
def __len__(self):
return len(self._state)
def clear(self):
self._state.clear()
logger.info("Cleared all state")
def get(self, key: Key, default: Any = None) -> Any:
return self._state.get(key, default)
def items(self) -> ItemsView[Key, Any]:
return self._state.items()
def keys(self) -> KeysView[Key]:
return self._state.keys()
def pop(self, key: Key, default: Any = None) -> Any:
value = self._state.pop(key, default)
logger.info(f"Popped {key} = {value}")
return value
def popitem(self) -> Any:
item = self._state.popitem()
logger.info(f"Popped item {item}")
return item
def setdefault(self, key: Key, default: Any = None) -> Any:
value = self._state.setdefault(key, default)
logger.info(f"Set default {key} = {value}")
return value
def to_dict(self) -> Dict[Key, Any]:
return dict(self._state)
def update(self, *args, **kwargs):
self._state.update(*args, **kwargs)
logger.info(f"Updated state with {args}, {kwargs}")
def values(self) -> ValuesView[Any]:
return self._state.values()
def initialize_state(at: Literal["cli", "web"]) -> State:
return State(at)
# Initialize the global state
state: State = initialize_state("cli")