Below is a production-ready Python class implementation for a simple data storage system. This class uses SQLite as the underlying database, which is suitable for handling concurrent access from multiple Python processes. SQLite manages concurrency through file-level locking, ensuring that writes are serialized to prevent data corruption, while allowing multiple reads simultaneously.
Key Features:
- Storage: Data is stored using two strings:
key1 (which should be one of 7 predefined options—I've included basic validation for this) and key2. Each entry automatically includes the current timestamp.
- Retrieval: You can retrieve entries by querying on
key1 (required) and optionally key2. The method returns a list of matching entries, each as a dictionary containing key1, key2, and the stored timestamp.
- Concurrency: SQLite handles multiple processes accessing the same database file. Each process will have its own connection, and the database will manage locks.
- Error Handling: Basic error handling is included to manage common issues like database errors or invalid inputs.
- Validation:
key1 is validated against a list of 7 options (e.g., ["option1", "option2", ..., "option7"]). You can customize this list in the class.
- Timestamp: Uses the current UTC timestamp for consistency across processes.
Dependencies:
sqlite3: Built into Python's standard library.
datetime: For handling timestamps.
Usage Example:
# In one process
storage = SimpleDataStorage(db_path="data.db")
storage.store(key1="option1", key2="some_value") # Stores with current timestamp
# In another process (concurrent)
storage2 = SimpleDataStorage(db_path="data.db")
results = storage2.retrieve(key1="option1") # Retrieves all entries for key1="option1"
for entry in results:
print(entry) # e.g., {'key1': 'option1', 'key2': 'some_value', 'timestamp': '2023-10-01T12:00:00.000000'}
Important Notes:
- Database File: The database is stored in a file specified by
db_path. Ensure this file is in a shared location if processes are on the same machine. If processes are on different machines, you'd need a networked file system or a more advanced database.
- Concurrency Limitations: While SQLite works for low to moderate concurrency, high-contention scenarios might lead to delays. If you need more robust concurrency, consider PostgreSQL or MongoDB.
- Thread Safety: This implementation is process-safe but not thread-safe within a single process. If you need thread safety, use a connection pool or serialize access.
- Data Persistence: The database persists across runs, but you can add a method to clear or backup data if needed.
Here's the code:
import sqlite3
from datetime import datetime
import os
class SimpleDataStorage:
# Define the 7 options for key1; you can modify this as needed
ALLOWED_KEY1_OPTIONS = ["option1", "option2", "option3", "option4", "option5", "option6", "option7"]
def __init__(self, db_path: str):
"""
Initialize the data storage.
:param db_path: Path to the SQLite database file.
"""
self.db_path = db_path
self.create_table() # Ensure the table exists
def create_table(self):
"""
Create the database table if it doesn't exist.
"""
with sqlite3.connect(self.db_path) as conn:
cursor = conn.cursor()
cursor.execute('''
CREATE TABLE IF NOT EXISTS data (
id INTEGER PRIMARY KEY AUTOINCREMENT,
key1 TEXT NOT NULL,
key2 TEXT NOT NULL,
timestamp TEXT NOT NULL
)
''')
conn.commit()
def store(self, key1: str, key2: str):
"""
Store data with the current timestamp.
:param key1: The first string (must be one of the 7 predefined options).
:param key2: The second string.
:raises ValueError: If key1 is not in the allowed options.
:raises sqlite3.Error: If there's a database error.
"""
if key1 not in self.ALLOWED_KEY1_OPTIONS:
raise ValueError(f"key1 must be one of: {self.ALLOWED_KEY1_OPTIONS}")
timestamp = datetime.utcnow().isoformat() # Use UTC for consistency
try:
with sqlite3.connect(self.db_path) as conn:
cursor = conn.cursor()
cursor.execute('''
INSERT INTO data (key1, key2, timestamp)
VALUES (?, ?, ?)
''', (key1, key2, timestamp))
conn.commit()
except sqlite3.Error as e:
raise sqlite3.Error(f"Error storing data: {e}")
def retrieve(self, key1: str, key2: str = None) -> list:
"""
Retrieve all entries that match the query, ordered by timestamp (ascending).
:param key1: The first string to match (required).
:param key2: The second string to match (optional).
:return: A list of dictionaries, each containing 'key1', 'key2', and 'timestamp'.
:raises ValueError: If key1 is not in the allowed options.
:raises sqlite3.Error: If there's a database error.
"""
if key1 not in self.ALLOWED_KEY1_OPTIONS:
raise ValueError(f"key1 must be one of: {self.ALLOWED_KEY1_OPTIONS}")
try:
with sqlite3.connect(self.db_path) as conn:
cursor = conn.cursor()
if key2 is None:
# Match only key1
cursor.execute('''
SELECT key1, key2, timestamp FROM data
WHERE key1 = ?
ORDER BY timestamp ASC
''', (key1,))
else:
# Match both key1 and key2
cursor.execute('''
SELECT key1, key2, timestamp FROM data
WHERE key1 = ? AND key2 = ?
ORDER BY timestamp ASC
''', (key1, key2))
rows = cursor.fetchall()
return [{'key1': row[0], 'key2': row[1], 'timestamp': row[2]} for row in rows]
except sqlite3.Error as e:
raise sqlite3.Error(f"Error retrieving data: {e}")
# Example usage (as shown earlier)
if __name__ == "__main__":
# This block is for testing; it won't run in imported modules
storage = SimpleDataStorage(db_path="data.db")
storage.store(key1="option1", key2="value1") # Stores an entry
results = storage.retrieve(key1="option1")
print(results) # Output: [{'key1': 'option1', 'key2': 'value1', 'timestamp': '2023-10-01T12:00:00.000000'}]
Explanation of the Code:
- Constructor (
__init__): Initializes the database by calling create_table(). This ensures the table is created if it doesn't exist.
- Store Method (
store): Validates key1, generates a UTC timestamp, and inserts the data into the database. Uses a context manager to handle the connection.
- Retrieve Method (
retrieve): Validates key1, queries the database based on the provided parameters, and returns the results as a list of dictionaries. Results are ordered by timestamp for consistency.
- Error Handling: Catches SQLite errors and raises them with a descriptive message. Also validates inputs to prevent invalid data.
- Timestamp Handling: Stored as an ISO-formatted string (e.g., "2023-10-01T12:00:00.000000") for easy readability and sorting.
This implementation is simple, efficient, and ready for use in a production environment with multiple processes. If you need additional features (e.g., deletion, updates, or more advanced querying), let me know!