Skip to content

Instantly share code, notes, and snippets.

@old-adapdr
Last active December 9, 2022 18:26
Show Gist options
  • Save old-adapdr/293ab3b28d9eb0bc0cf1ff036a41867d to your computer and use it in GitHub Desktop.
Save old-adapdr/293ab3b28d9eb0bc0cf1ff036a41867d to your computer and use it in GitHub Desktop.
Python native key/value storage
"""
This file contains helper functions for the built-in
python (key, value) storage
"""
import dbm
from secrets import token_urlsafe
from logging import getLogger
from typing import Union, Tuple
logger = getLogger(__name__)
def store(value: Union[str, bytes], length: int, key: str = None) -> str:
"""
Method stores the value using the provided key, or with a generated one.
Arguement(s):
- key: <str> (optional) identifying key for the value
- length: <int> length of the generated key
- value: <Union[str, bytes]> value to store
Returns
- key: <str> the key used
"""
try: # To store value to kv-storage
if value not str or value not bytes: # Then it's invalid
raise ValueError
if key is None: # Then generate it
key = token_urlsafe(length or None)
# Default
with dbm.open('database/storage') as storage:
storage[key] = value
except ValueError:
logger.exception('Value has to be str or bytes!')
def get(key: str) -> Tuple[str, Union[str, bytes]]:
"""
Method retrieves value by key.
Arguement(s):
- key: (str) key to retrieve value with
Returns:
- Tuple[str, Union[str, bytes]] returns a key,value pair as a tuple
"""
try: # To store value to kv-storage
with dbm.open('database/storage') as storage:
storage[key] = value
except KeyError:
msg: str = f"Invalid key used: '{key}'"
logger.exception(msg)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment