memory-oc 1.0.1__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
memory/__init__.py ADDED
@@ -0,0 +1,314 @@
1
+ # coding=utf8
2
+ """ Memory
3
+
4
+ Handles internal sessions shared across requests
5
+ """
6
+ from __future__ import annotations
7
+
8
+ __author__ = "Chris Nasr"
9
+ __copyright__ = "Ouroboros Coding Inc."
10
+ __email__ = "chris@ouroboroscoding.com"
11
+ __created__ = "2023-03-15"
12
+
13
+ # Limit exports
14
+ __all__ = ['create', 'init', 'load']
15
+
16
+ # Ouroboros imports
17
+ from config import config
18
+ import jobject
19
+ import jsonb
20
+ from nredis import nr
21
+ from strings import random
22
+
23
+ # Pip imports
24
+ import json_fix
25
+
26
+ # Open redis connection
27
+ _moRedis = nr(config.memory.redis('session'))
28
+
29
+ def create(key: str = None, ttl: int = 0) -> _Memory:
30
+ """Create
31
+
32
+ Returns a brand new session using the key given, else a UUID is generated
33
+
34
+ Arguments:
35
+ key (str): The key to use for the session
36
+ ttl (uint): Time to live, a specific expiry time in seconds
37
+
38
+ Returns:
39
+ _Memory
40
+ """
41
+
42
+ # Init the data with the expires time
43
+ dData = { '__ttl': ttl }
44
+
45
+ # If we were passed a key
46
+ if key:
47
+
48
+ # If it exists
49
+ if _moRedis.exists(key):
50
+ raise RuntimeError('memory_oc', key, 'key exists')
51
+
52
+ # Set the key
53
+ sKey = key
54
+
55
+ # Else, loop till we get a key that works, which theoretically is always the
56
+ # first time, but on the off chance something breaks, let's have it fully
57
+ # break instead of running forever eating up resources.
58
+ i = 0
59
+ while True:
60
+
61
+ # Generate a random key
62
+ sKey = 's:%s' % random(32, [ 'aZ', '10', '!*' ])
63
+
64
+ # If it doesn't exist, break out of the loop
65
+ if not _moRedis.exists(sKey):
66
+ break
67
+
68
+ # Increment the count
69
+ i += 1
70
+ if i > 10:
71
+ raise RuntimeError(
72
+ 'memory_oc', 'potential infinite loop in create()'
73
+ )
74
+
75
+ # Create a new Memory using the passed key, or a new UUID
76
+ return _Memory(sKey, dData)
77
+
78
+ def load(key: str) -> _Memory:
79
+ """Load
80
+
81
+ Loads an existing session from the cache
82
+
83
+ Arguments:
84
+ key (str): The unique id of an existing session
85
+
86
+ Returns:
87
+ _Memory
88
+ """
89
+
90
+ # Fetch from Redis
91
+ s = _moRedis.get(key)
92
+
93
+ # If there's no session or it expired
94
+ if s == None: return None
95
+
96
+ # Make sure we have a string, not a set of bytes
97
+ try: s = s.decode()
98
+ except (UnicodeDecodeError, AttributeError): pass
99
+
100
+ # Create a new instance with the decoded data
101
+ return _Memory(key, jsonb.decode(s))
102
+
103
+ class _Memory(object):
104
+ """Memory
105
+
106
+ A wrapper for the session data
107
+
108
+ Extends:
109
+ object
110
+ """
111
+
112
+ def __init__(self, key: str, data: dict = {}):
113
+ """Constructor
114
+
115
+ Intialises the instance, which is just setting up the dict
116
+
117
+ Arguments:
118
+ key (str): The key used to access or store the session
119
+ data (dict): The data in the session
120
+
121
+ Returns:
122
+ _Memory
123
+ """
124
+
125
+ # Store the key and data
126
+ object.__setattr__(self, '__key', key)
127
+ object.__setattr__(self, '__store', jobject(data))
128
+
129
+ def __contains__(self, key: str):
130
+ """__contains__
131
+
132
+ True if the key exists in the session
133
+
134
+ Arguments:
135
+ key (str): The field to check for
136
+
137
+ Returns:
138
+ bool
139
+ """
140
+ return object.__getattribute__(self, '__store').__contains__(key)
141
+
142
+ def __delitem__(self, k):
143
+ """__delete__
144
+
145
+ Removes a key from a session
146
+
147
+ Arguments:
148
+ k (str): The key to remove
149
+
150
+ Returns:
151
+ None
152
+ """
153
+ del object.__getattribute__(self, '__store')[k]
154
+
155
+ def __getattr__(self, a: str) -> any:
156
+ """__getattr__
157
+
158
+ Gives object notation access to get the internal dict keys
159
+
160
+ Arguments:
161
+ a (str): The attribute to get
162
+
163
+ Raises:
164
+ AttributeError
165
+
166
+ Returns:
167
+ any
168
+ """
169
+ try:
170
+ return object.__getattribute__(self, '__store')[a]
171
+ except KeyError:
172
+ raise AttributeError(a, '%s not in Memory instance' % a)
173
+
174
+ def __getitem__(self, k):
175
+ """__getitem__
176
+
177
+ Returns the given key
178
+
179
+ Arguments:
180
+ k (str): The key to return
181
+
182
+ Returns:
183
+ any
184
+ """
185
+ return object.__getattribute__(self, '__store').__getitem__(k)
186
+
187
+ def __iter__(self):
188
+ """__iter__
189
+
190
+ Returns an iterator for the internal dict
191
+
192
+ Returns:
193
+ iterator
194
+ """
195
+ return object.__getattribute__(self, '__store').__iter__()
196
+
197
+ def __json__(self):
198
+ """__json__
199
+
200
+ Returns a dict representation of the session
201
+
202
+ Returns:
203
+ dict
204
+ """
205
+ return {
206
+ '__key': object.__getattribute__(self, '__key'),
207
+ '__store': object.__getattribute__(self, '__store')
208
+ }
209
+
210
+ def __len__(self):
211
+ """__len__
212
+
213
+ Return the length of the internal dict
214
+
215
+ Returns:
216
+ uint
217
+ """
218
+ return object.__getattribute__(self, '__store').__len__()
219
+
220
+ def __setattr__(self, a: str, v: any) -> None:
221
+ """__setattr__
222
+
223
+ Gives object notation access to set the internal dict keys
224
+
225
+ Arguments:
226
+ a (str): The key in the dict to set
227
+ v (any): The value to set on the key
228
+ """
229
+ object.__getattribute__(self, '__store').__setitem__(a, v)
230
+
231
+ def __setitem__(self, k, v):
232
+ """__setitem__
233
+
234
+ Sets the given key
235
+
236
+ Arguments:
237
+ k (str): The key to set
238
+ v (any): The value for the key
239
+ """
240
+ object.__getattribute__(self, '__store').__setitem__(k, v)
241
+
242
+ def __str__(self):
243
+ """__str__
244
+
245
+ Returns a string representation of the internal dict
246
+
247
+ Returns:
248
+ str
249
+ """
250
+ return object.__getattribute__(self, '__store').__str__()
251
+
252
+ def close(self):
253
+ """Close
254
+
255
+ Deletes the session from the cache
256
+
257
+ Returns:
258
+ None
259
+ """
260
+ _moRedis.delete(object.__getattribute__(self, '__key'))
261
+
262
+ def extend(self):
263
+ """Extend
264
+
265
+ Keep the session alive by extending it's expire time by the internally \
266
+ set expire value, or else by the global one set for the module
267
+
268
+ Returns:
269
+ None
270
+ """
271
+
272
+ # If the expire time is 0, do nothing
273
+ if object.__getattribute__(self, '__store')['__ttl'] == 0:
274
+ return
275
+
276
+ # Extend the session in Redis
277
+ _moRedis.expire(
278
+ object.__getattribute__(self, '__key'),
279
+ object.__getattribute__(self, '__store')['__ttl']
280
+ )
281
+
282
+ def key(self):
283
+ """Key
284
+
285
+ Returns the key of the session
286
+
287
+ Returns:
288
+ str
289
+ """
290
+ return object.__getattribute__(self, '__key')
291
+
292
+ def save(self):
293
+ """Save
294
+
295
+ Saves the current session data in the cache
296
+
297
+ Returns:
298
+ None
299
+ """
300
+
301
+ # If we have no expire time, set forever
302
+ if object.__getattribute__(self, '__store')['__ttl'] == 0:
303
+ _moRedis.set(
304
+ object.__getattribute__(self, '__key'),
305
+ jsonb.encode(object.__getattribute__(self, '__store'))
306
+ )
307
+
308
+ # Else, set to expire
309
+ else:
310
+ _moRedis.setex(
311
+ object.__getattribute__(self, '__key'),
312
+ object.__getattribute__(self, '__store')['__ttl'],
313
+ jsonb.encode(object.__getattribute__(self, '__store'))
314
+ )
memory/__main__.py ADDED
@@ -0,0 +1 @@
1
+ print('I compile, but I don\'t necessarily run')
@@ -0,0 +1,20 @@
1
+ Metadata-Version: 2.4
2
+ Name: memory_oc
3
+ Version: 1.0.1
4
+ Summary: A session library using redis
5
+ Project-URL: Source, https://github.com/ouroboroscoding/memory-python
6
+ Project-URL: Tracker, https://github.com/ouroboroscoding/memory-python/issues
7
+ Author-email: "Chris Nasr - Ouroboros Coding Inc." <chris@ouroboroscoding.com>
8
+ Maintainer-email: "Chris Nasr - Ouroboros Coding Inc." <chris@ouroboroscoding.com>
9
+ License-Expression: MIT
10
+ License-File: LICENSE
11
+ Requires-Python: >=3.10
12
+ Requires-Dist: jobject<1.1,>=1.0.4
13
+ Requires-Dist: json-fix<1.1,>=1.0.0
14
+ Requires-Dist: jsonb<1.1,>=1.0.0
15
+ Requires-Dist: namedredis<1.1,>=1.0.2
16
+ Requires-Dist: strings-oc<1.1,>=1.0.7
17
+ Description-Content-Type: text/markdown
18
+
19
+ # memory-python
20
+ A python session library using redis
@@ -0,0 +1,6 @@
1
+ memory/__init__.py,sha256=BW7KeQhYxo-nbFCPNJn8T9_7WMV1s4Thoc5qkjWIIao,6178
2
+ memory/__main__.py,sha256=qxPLqwdqExh6ARRJNMD8bgD4VMoM96_s82rVexMfyJs,48
3
+ memory_oc-1.0.1.dist-info/METADATA,sha256=zO9XWA4pHAcsG-EWVsiJ02oKaxKJFH9GusCOYlu0qzA,745
4
+ memory_oc-1.0.1.dist-info/WHEEL,sha256=qtCwoSJWgHk21S1Kb4ihdzI2rlJ1ZKaIurTj_ngOhyQ,87
5
+ memory_oc-1.0.1.dist-info/licenses/LICENSE,sha256=xYhGaO0OPR5x6-t7yUo8tZTGQSsL9uE8aAtWg-zHayE,1077
6
+ memory_oc-1.0.1.dist-info/RECORD,,
@@ -0,0 +1,4 @@
1
+ Wheel-Version: 1.0
2
+ Generator: hatchling 1.27.0
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2025 Ouroboros Coding Inc.
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.