pickleDB is lightweight, fast, and simple database based on the json module. And it's BSD licensed!
>>> import pickledb
>>> db = pickledb.load('test.db', False)
>>> db.set('key', 'value')
>>> db.get('key')
'value'
>>> db.dump()
True
- Just add the
pickledb.py
file to your working directory or usepip install pickledb
. - pickleDB also includes a simplified and faster version using orjson called
pkldb.py
, to use this add it to your working directory and note the slight difference in setupfrom pkldb.py import pkldb
thendb = pkldb('example.json')
PickleDB is a lightweight, file-based key-value store with optional support for time-to-live (TTL). It provides a simple and intuitive API for storing and managing data persistently.
- Basic Usage
- Key-Value Methods
- List Methods
- Dictionary Methods
- Enhanced Features
from pickledb_enhanced import load
db = load('mydb.json', auto_dump=True, enable_ttl=True)
auto_dump
: Automatically save changes to the file.enable_ttl
: Enable TTL support for expiring keys.
Set a key-value pair in the database.
Retrieve the value associated with a key.
Check if a key exists.
Remove a key from the database.
Get all keys in the database.
Clear all keys.
Delete the database file.
Create a new list in the database.
Add a value to an existing list.
Retrieve all values from a list.
Sort a list in ascending or descending order.
reverse
: Sort in descending order ifTrue
.
Remove a value from a list.
Retrieve a range of values from a list.
start
: Start index.end
: End index.
Get the length of a list.
Create a new dictionary in the database.
Add a key-value pair to a dictionary.
Retrieve a value from a dictionary.
Retrieve all key-value pairs from a dictionary.
Remove a key from a dictionary.
Merge another dictionary into an existing dictionary.
Get all keys from a dictionary.
Get all values from a dictionary.
- Expire keys automatically after a given time.
- Compress the database file to save space.
- Save changes automatically using
auto_dump
.
# Create a list and add values
db.lcreate('mylist')
db.ladd('mylist', 'item1')
db.ladd('mylist', 'item2')
# Sort the list
db.lsort('mylist') # ['item1', 'item2']
# Get a range of values
db.lgetrange('mylist', 0, 1) # ['item1']
# Remove an item
db.lremove('mylist', 'item1')
# Create a dictionary and add values
db.dcreate('mydict')
db.dadd('mydict', 'key1', 'value1')
db.dadd('mydict', 'key2', 'value2')
# Merge another dictionary
db.dmerge('mydict', {'key3': 'value3'})
# Get all keys and values
db.dkeys('mydict') # ['key1', 'key2', 'key3']
db.dvalues('mydict') # ['value1', 'value2', 'value3']
# Remove a key
db.dremove('mydict', 'key1')
- Always ensure proper file permissions for the database file.
- Use thread-safe practices when accessing the database concurrently.
- Enhanced Features: Added methods for list sorting, removal, range fetching, and dictionary merging.