Add support for directory creation and binary files

- Use the `Path` module instead of `os`
- Add ability to create any amount of missing directories for a given file
- Add ability to save both text and binary files to save images (or other file types) later
This commit is contained in:
Enzo Martin
2023-06-18 10:05:59 +02:00
parent b97563726f
commit 50c505c459

View File

@@ -1,35 +1,52 @@
from dataclasses import dataclass
import os
from pathlib import Path
# This class represents a simple database that stores its data as files in a directory.
# It supports both text and binary files, and can handle directory structures.
class DB:
"""A simple key-value store, where keys are filenames and values are file contents."""
def __init__(self, path):
# Convert the path string to a Path object and get its absolute path.
self.path = Path(path).absolute()
os.makedirs(self.path, exist_ok=True)
# Create the directory if it doesn't exist.
self.path.mkdir(parents=True, exist_ok=True)
def __getitem__(self, key):
with open(self.path / key, encoding='utf-8') as f:
return f.read()
# Combine the database directory with the provided file path.
full_path = self.path / key
# Check if the file exists before trying to open it.
if full_path.is_file():
# Open the file in text mode and return its content.
with full_path.open('r') as f:
return f.read()
else:
# If the file doesn't exist, raise an error.
raise FileNotFoundError(f"No such file: '{full_path}'")
def __setitem__(self, key, val):
Path(self.path / key).absolute().parent.mkdir(parents=True, exist_ok=True)
# Combine the database directory with the provided file path.
full_path = self.path / key
with open(self.path / key, 'w', encoding='utf-8') as f:
f.write(val)
# Create the directory tree if it doesn't exist.
full_path.parent.mkdir(parents=True, exist_ok=True)
def __contains__(self, key):
return (self.path / key).exists()
# Write the data to the file. If val is a string, it's written as text.
# If val is bytes, it's written as binary data.
if isinstance(val, str):
full_path.write_text(val)
elif isinstance(val, bytes):
full_path.write_bytes(val)
else:
# If val is neither a string nor bytes, raise an error.
raise TypeError("val must be either a str or bytes")
# dataclass for all dbs:
@dataclass
class DBs:
"""A dataclass for all dbs"""
memory: DB
logs: DB
identity: DB
input: DB
workspace: DB
workspace: DB