Skip to content

Instantly share code, notes, and snippets.

@frainfreeze
Created July 14, 2023 16:15
Show Gist options
  • Save frainfreeze/f4457fe24a49f1a49c7129748014843d to your computer and use it in GitHub Desktop.
Save frainfreeze/f4457fe24a49f1a49c7129748014843d to your computer and use it in GitHub Desktop.
import shelve
from pathlib import Path
from flask import Flask, has_app_context
class ShelveDB:
"""
Use shelve as simple DB. Supports flask.
>>> db = ShelveDB(app)
>>> db['example'] = 'Hello, world!'
>>> db['example']
'Hello, world!'
"""
def __init__(self, location: str = None, app: Flask | None = None):
if app is not None:
self.location: str = app.config["SHELVE_DATABASE_URI"]
else:
self.location: str = str(Path.cwd())
def __repr__(self) -> str:
return f"{type(self).__name__} {self.location}"
def __getitem__(self, key):
with shelve.open(self.location, "c", writeback=True) as db:
fetched_key = db.get(str(key), None)
if not fetched_key:
raise KeyError
return fetched_key
def __setitem__(self, key, value):
with shelve.open(self.location, "c", writeback=True) as db:
db[str(key)] = str(value)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment