memory-oc 1.0.2__tar.gz → 1.0.3__tar.gz

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.
@@ -1,6 +1,6 @@
1
- Metadata-Version: 2.4
1
+ Metadata-Version: 2.5
2
2
  Name: memory_oc
3
- Version: 1.0.2
3
+ Version: 1.0.3
4
4
  Summary: A session library using redis
5
5
  Project-URL: Source, https://github.com/ouroboroscoding/memory-python
6
6
  Project-URL: Tracker, https://github.com/ouroboroscoding/memory-python/issues
@@ -40,6 +40,7 @@ for changes from release to release.
40
40
  - [extend](#instance-extend)
41
41
  - [key](#instance-key)
42
42
  - [save](#instance-save)
43
+ - [ttl](#instance-ttl)
43
44
  - [update](#instance-update)
44
45
 
45
46
  ## Module Install
@@ -200,6 +201,24 @@ session['name'] = 'Samuel'
200
201
  session.save()
201
202
  ```
202
203
 
204
+ ### instance.ttl
205
+ Getter / Setter for the TTL on the session.
206
+
207
+ #### example
208
+ Set
209
+ ```python
210
+ import memory
211
+
212
+ # Load session
213
+ session = memory.load(somekey)
214
+
215
+ # Returns the current ttl
216
+ session.ttl()
217
+
218
+ # Updates the ttl to 5 minutes and refreshes the session
219
+ session.ttl(300)
220
+ ```
221
+
203
222
  ### instance.update
204
223
  Works the same as dict update() so you can store multiple keys at once
205
224
 
@@ -22,6 +22,7 @@ for changes from release to release.
22
22
  - [extend](#instance-extend)
23
23
  - [key](#instance-key)
24
24
  - [save](#instance-save)
25
+ - [ttl](#instance-ttl)
25
26
  - [update](#instance-update)
26
27
 
27
28
  ## Module Install
@@ -182,6 +183,24 @@ session['name'] = 'Samuel'
182
183
  session.save()
183
184
  ```
184
185
 
186
+ ### instance.ttl
187
+ Getter / Setter for the TTL on the session.
188
+
189
+ #### example
190
+ Set
191
+ ```python
192
+ import memory
193
+
194
+ # Load session
195
+ session = memory.load(somekey)
196
+
197
+ # Returns the current ttl
198
+ session.ttl()
199
+
200
+ # Updates the ttl to 5 minutes and refreshes the session
201
+ session.ttl(300)
202
+ ```
203
+
185
204
  ### instance.update
186
205
  Works the same as dict update() so you can store multiple keys at once
187
206
 
@@ -11,7 +11,7 @@ __email__ = "chris@ouroboroscoding.com"
11
11
  __created__ = "2023-03-15"
12
12
 
13
13
  # Limit exports
14
- __all__ = ['create', 'init', 'load']
14
+ __all__ = [ 'close', 'create', 'load' ]
15
15
 
16
16
  # Ouroboros imports
17
17
  from config import config
@@ -21,6 +21,9 @@ from nredis import nr
21
21
  from strings import random
22
22
  from tools import combine
23
23
 
24
+ # Python imports
25
+ from copy import deepcopy
26
+
24
27
  # Pip imports
25
28
  import json_fix
26
29
 
@@ -37,16 +40,22 @@ def close(key: str):
37
40
  def create(key: str = None, ttl: int = 0, data = None) -> _Memory:
38
41
  """Create
39
42
 
40
- Returns a brand new session using the key given, else a UUID is generated
43
+ Returns a brand new session using the key given, else a random key is
44
+ generated.
41
45
 
42
46
  Arguments:
43
47
  key (str): The key to use for the session
44
48
  ttl (uint): Time to live, a specific expiry time in seconds
49
+ data (dict): Initial data in the session
45
50
 
46
51
  Returns:
47
52
  _Memory
48
53
  """
49
54
 
55
+ # If the ttl is not an unsigned int
56
+ if isinstance(ttl, bool) or not isinstance(ttl, int) or ttl < 0:
57
+ raise ValueError('ttl must be an unsigned int')
58
+
50
59
  # Generate the data to store by adding the TTL
51
60
  dData = (
52
61
  data is None
@@ -59,7 +68,7 @@ def create(key: str = None, ttl: int = 0, data = None) -> _Memory:
59
68
 
60
69
  # If it exists
61
70
  if _moRedis.exists(key):
62
- raise RuntimeError('memory_oc', key, 'key exists')
71
+ raise RuntimeError(f'memory_oc: "{key}" exists')
63
72
 
64
73
  # Set the key
65
74
  sKey = key
@@ -82,16 +91,16 @@ def create(key: str = None, ttl: int = 0, data = None) -> _Memory:
82
91
  i += 1
83
92
  if i > 10:
84
93
  raise RuntimeError(
85
- 'memory_oc', 'potential infinite loop in create()'
94
+ 'memory_oc, potential infinite loop in create()'
86
95
  )
87
96
 
88
- # Create a new Memory using the passed key, or a new UUID
97
+ # Create a new Memory using the passed key, or a new random string
89
98
  return _Memory(sKey, dData)
90
99
 
91
- def load(key: str) -> _Memory:
100
+ def load(key: str) -> _Memory | None:
92
101
  """Load
93
102
 
94
- Loads an existing session from the cache
103
+ Loads an existing session from the cache, or None if it doesn't exist.
95
104
 
96
105
  Arguments:
97
106
  key (str): The unique id of an existing session
@@ -116,13 +125,13 @@ def load(key: str) -> _Memory:
116
125
  class _Memory(object):
117
126
  """Memory
118
127
 
119
- A wrapper for the session data
128
+ A wrapper for the session data.
120
129
 
121
130
  Extends:
122
131
  object
123
132
  """
124
133
 
125
- def __init__(self, key: str, data: dict = None):
134
+ def __init__(self, key: str, data: dict | None = None) -> _Memory:
126
135
  """Constructor
127
136
 
128
137
  Intialises the instance, which is just setting up the dict
@@ -146,7 +155,7 @@ class _Memory(object):
146
155
  def __contains__(self, key: str):
147
156
  """__contains__
148
157
 
149
- True if the key exists in the session
158
+ True if the key exists in the session.
150
159
 
151
160
  Arguments:
152
161
  key (str): The field to check for
@@ -156,20 +165,25 @@ class _Memory(object):
156
165
  """
157
166
  return object.__getattribute__(self, '__store').__contains__(key)
158
167
 
159
- def __delitem__(self, k):
168
+ def __delitem__(self, k: str):
160
169
  """__delete__
161
170
 
162
- Removes a key from a session
171
+ Removes a key from a session.
163
172
 
164
173
  Arguments:
165
174
  k (str): The key to remove
166
175
  """
176
+
177
+ # Don't allow special keys to be changed
178
+ if isinstance(k, str) and k.startswith('__'):
179
+ raise KeyError(f'{k} is read-only')
180
+
167
181
  del object.__getattribute__(self, '__store')[k]
168
182
 
169
183
  def __getattr__(self, a: str) -> any:
170
184
  """__getattr__
171
185
 
172
- Gives object notation access to get the internal dict keys
186
+ Gives object notation access to get the internal dict keys.
173
187
 
174
188
  Arguments:
175
189
  a (str): The attribute to get
@@ -180,15 +194,23 @@ class _Memory(object):
180
194
  Returns:
181
195
  any
182
196
  """
197
+
198
+ # Check for store, likely to exist, but necessary for some libraries
199
+ try:
200
+ dStore = object.__getattribute__(self, '__store')
201
+ except AttributeError:
202
+ raise AttributeError(a) from None
203
+
204
+ # Try the actual attribute
183
205
  try:
184
- return object.__getattribute__(self, '__store')[a]
206
+ return dStore[a]
185
207
  except KeyError:
186
- raise AttributeError(a, '%s not in Memory instance' % a)
208
+ raise AttributeError(f'{a} not in Memory instance') from None
187
209
 
188
210
  def __getitem__(self, k):
189
211
  """__getitem__
190
212
 
191
- Returns the given key
213
+ Returns the given key.
192
214
 
193
215
  Arguments:
194
216
  k (str): The key to return
@@ -201,7 +223,7 @@ class _Memory(object):
201
223
  def __iter__(self):
202
224
  """__iter__
203
225
 
204
- Returns an iterator for the internal dict
226
+ Returns an iterator for the internal dict.
205
227
 
206
228
  Returns:
207
229
  iterator
@@ -211,20 +233,20 @@ class _Memory(object):
211
233
  def __json__(self):
212
234
  """__json__
213
235
 
214
- Returns a dict representation of the session
236
+ Returns a dict representation of the session.
215
237
 
216
238
  Returns:
217
239
  dict
218
240
  """
219
241
  return {
220
242
  '__key': object.__getattribute__(self, '__key'),
221
- '__store': object.__getattribute__(self, '__store')
243
+ '__store': deepcopy(object.__getattribute__(self, '__store'))
222
244
  }
223
245
 
224
246
  def __len__(self):
225
247
  """__len__
226
248
 
227
- Return the length of the internal dict
249
+ Return the length of the internal dict.
228
250
 
229
251
  Returns:
230
252
  uint
@@ -234,29 +256,41 @@ class _Memory(object):
234
256
  def __setattr__(self, a: str, v: any) -> None:
235
257
  """__setattr__
236
258
 
237
- Gives object notation access to set the internal dict keys
259
+ Gives object notation access to set the internal dict keys.
238
260
 
239
261
  Arguments:
240
262
  a (str): The key in the dict to set
241
263
  v (any): The value to set on the key
242
264
  """
265
+
266
+ # Don't allow special keys to be changed
267
+ if a.startswith('__'):
268
+ raise KeyError(f'{a} is read-only')
269
+
270
+ # Set the item
243
271
  object.__getattribute__(self, '__store').__setitem__(a, v)
244
272
 
245
- def __setitem__(self, k, v):
273
+ def __setitem__(self, k: str, v: any):
246
274
  """__setitem__
247
275
 
248
- Sets the given key
276
+ Sets the given key.
249
277
 
250
278
  Arguments:
251
279
  k (str): The key to set
252
280
  v (any): The value for the key
253
281
  """
282
+
283
+ # Don't allow special keys to be changed
284
+ if isinstance(k, str) and k.startswith('__'):
285
+ raise KeyError(f'{k} is read-only')
286
+
287
+ # Set the item
254
288
  object.__getattribute__(self, '__store').__setitem__(k, v)
255
289
 
256
290
  def __str__(self):
257
291
  """__str__
258
292
 
259
- Returns a string representation of the internal dict
293
+ Returns a string representation of the internal dict.
260
294
 
261
295
  Returns:
262
296
  str
@@ -266,31 +300,31 @@ class _Memory(object):
266
300
  def close(self):
267
301
  """Close
268
302
 
269
- Deletes the session from the cache
303
+ Deletes the session from the cache.
270
304
  """
271
305
  _moRedis.delete(object.__getattribute__(self, '__key'))
272
306
 
273
307
  def extend(self):
274
308
  """Extend
275
309
 
276
- Keep the session alive by extending it's expire time by the internally \
277
- set expire value, or else by the global one set for the module
310
+ Keep the session alive by extending it's expire time by the internally
311
+ set expire value, or else by the global one set for the module.
278
312
  """
279
313
 
314
+ # Get the store
315
+ dStore = object.__getattribute__(self, '__store')
316
+
280
317
  # If the expire time is 0, do nothing
281
- if object.__getattribute__(self, '__store')['__ttl'] == 0:
318
+ if dStore['__ttl'] == 0:
282
319
  return
283
320
 
284
321
  # Extend the session in Redis
285
- _moRedis.expire(
286
- object.__getattribute__(self, '__key'),
287
- object.__getattribute__(self, '__store')['__ttl']
288
- )
322
+ _moRedis.expire(object.__getattribute__(self, '__key'), dStore['__ttl'])
289
323
 
290
- def key(self):
324
+ def key(self) -> str:
291
325
  """Key
292
326
 
293
- Returns the key of the session
327
+ Returns the key of the session.
294
328
 
295
329
  Returns:
296
330
  str
@@ -300,31 +334,67 @@ class _Memory(object):
300
334
  def save(self):
301
335
  """Save
302
336
 
303
- Saves the current session data in the cache
337
+ Saves the current session data in the cache.
304
338
  """
305
339
 
340
+ # Get the store
341
+ dStore = object.__getattribute__(self, '__store')
342
+
343
+ # Encode it
344
+ dJSON = jsonb.encode(dStore)
345
+
306
346
  # If we have no expire time, set forever
307
- if object.__getattribute__(self, '__store')['__ttl'] == 0:
308
- _moRedis.set(
309
- object.__getattribute__(self, '__key'),
310
- jsonb.encode(object.__getattribute__(self, '__store'))
311
- )
347
+ if dStore['__ttl'] == 0:
348
+ _moRedis.set(object.__getattribute__(self, '__key'), dJSON)
312
349
 
313
350
  # Else, set to expire
314
351
  else:
315
352
  _moRedis.setex(
316
353
  object.__getattribute__(self, '__key'),
317
- object.__getattribute__(self, '__store')['__ttl'],
318
- jsonb.encode(object.__getattribute__(self, '__store'))
354
+ dStore['__ttl'],
355
+ dJSON
319
356
  )
320
357
 
358
+ def ttl(self, ttl: int | None = None) -> int | None:
359
+ """TTL
360
+
361
+ Getter / Setter for the Time To Live in seconds of the session.
362
+
363
+ Arguments:
364
+ ttl (uint | None): Do not set to fetch the current value, set to 0
365
+ (zero) for a session that never expires, set to anything greater
366
+ than 0 (zero) to have it expired in `ttl` seconds
367
+
368
+ Returns:
369
+ uint | None
370
+ """
371
+
372
+ # Get the store
373
+ dStore = object.__getattribute__(self, '__store')
374
+
375
+ # If we are requesting the data
376
+ if ttl is None:
377
+ return dStore['__ttl']
378
+
379
+ # If we didn't get a number, or it's below 0
380
+ if isinstance(ttl, bool) or not isinstance(ttl, int) or ttl < 0:
381
+ raise ValueError('ttl must be an unsigned int')
382
+
383
+ # If the value hasn't changed
384
+ if ttl != dStore['__ttl']:
385
+ dStore['__ttl'] = ttl
386
+ self.save()
387
+
321
388
  def update(self, other = (), /, **kwargs):
322
389
  """Updated
323
390
 
324
391
  Merge key/value pairs into the session store. Works exactly like dict
325
- update()
392
+ update().
326
393
 
327
394
  Arguments:
328
395
  other (dict, list, **kwargs): The additional keys and values to add
329
396
  """
330
- object.__getattribute__(self, '__store').update(other, **kwargs)
397
+
398
+ # Run through each to guard against __ keys being set
399
+ for k, v in dict(other, **kwargs).items():
400
+ self[k] = v
@@ -4,7 +4,7 @@ build-backend = "hatchling.build"
4
4
 
5
5
  [project]
6
6
  name = "memory_oc"
7
- version = "1.0.2"
7
+ version = "1.0.3"
8
8
  description = "A session library using redis"
9
9
  authors = [
10
10
  {name = "Chris Nasr - Ouroboros Coding Inc.", email = "chris@ouroboroscoding.com"}
File without changes
File without changes
File without changes