### Install pickledb Source: https://github.com/patx/pickledb/blob/master/_autodocs/REFERENCE.md Install the core pickledb library using pip. For SQLite support, install with the 'sqlite' extra. ```bash pip install pickledb # With SQLite support pip install "pickledb[sqlite]" ``` -------------------------------- ### Get All Data Source: https://github.com/patx/pickledb/blob/master/docs/index.html Demonstrates how to retrieve all key-value pairs from the database. This can be useful for backups or full data inspection. ```python from pickleDB import PickleDB db = PickleDB('my_database.json', False) db.set('a', 1) db.set('b', 2) db.dump() print(db.getAll()) ``` -------------------------------- ### Use PickleDB in Async Code Source: https://github.com/patx/pickledb/blob/master/_autodocs/INDEX.md Provides an example of using PickleDB within an asynchronous context, demonstrating async set and get operations. ```python async with PickleDB("data.json") as db: await db.set("key", "value") value = await db.get("key") ``` -------------------------------- ### Example Usage of MISSING Sentinel Source: https://github.com/patx/pickledb/blob/master/_autodocs/types.md Demonstrates how the MISSING sentinel distinguishes between a missing key and a key with a None value when using the get method. It shows that providing MISSING or no default raises a KeyError, while providing None returns None. ```python MISSING = object() # ... (rest of the code from the source) ``` ```python from pickledb import MISSING, PickleDBSQLite kv = PickleDBSQLite() kv.set("key", "value") # When default is MISSING, raises KeyError on missing key try: result = kv.get("missing", default=MISSING) except KeyError: print("Not found") # When default is None, returns None on missing key result = kv.get("missing", default=None) # Returns None # When default is not specified, MISSING is implicit result = kv.get("missing") # Raises KeyError (same as default=MISSING) ``` -------------------------------- ### Dual Sync/Async Pattern Example Source: https://github.com/patx/pickledb/blob/master/_autodocs/REFERENCE.md Demonstrates how to use PickleDB methods in both synchronous and asynchronous code contexts. In async code, methods must be awaited; in sync code, they return directly. ```python from pickledb import PickleDB, in_async db = PickleDB("data.json") # In sync code: db.set("key", "value") # Returns bool directly # In async code: async def async_code(): await db.set("key", "value") # Must await ``` -------------------------------- ### Install pickledb[sqlite] for SQLite support Source: https://github.com/patx/pickledb/blob/master/_autodocs/errors.md This command installs the optional aiosqlite dependency required for PickleDBSQLite functionality. ```bash pip install "pickledb[sqlite]" ``` -------------------------------- ### Get All Keys (Async) Source: https://github.com/patx/pickledb/blob/master/_autodocs/api-reference/pickledb-sqlite.md Asynchronously retrieves all keys from the database in alphabetical order. Requires await. ```python # Async keys = await kv.all() ``` -------------------------------- ### Get All Keys (Sync) Source: https://github.com/patx/pickledb/blob/master/_autodocs/api-reference/pickledb-sqlite.md Retrieves all keys from the database in alphabetical order. Returns an empty list if the table is empty. ```python kv.set("a", 1) kv.set("b", 2) kv.set("c", 3) # Sync keys = kv.all() # ["a", "b", "c"] ``` -------------------------------- ### Sync and Async Method Usage Source: https://github.com/patx/pickledb/blob/master/_autodocs/INDEX.md Demonstrates how to use PickleDB methods in both synchronous and asynchronous contexts. No special setup is required for dual usage. ```python # Sync db.set("key", "value") # Async await db.set("key", "value") ``` -------------------------------- ### Initialize PickleDBSQLite and Set/Get Data Source: https://github.com/patx/pickledb/blob/master/_autodocs/api-reference/pickledb-sqlite.md Initializes a PickleDBSQLite instance, sets a key-value pair, and retrieves the value. Ensure the 'pickledb' library with the 'sqlite' extra is installed. ```python from pickledb import PickleDBSQLite kv = PickleDBSQLite("store.sqlite3") kv.set("user:1", {"name": "Alice", "age": 30}) print(kv.get("user:1")) # {"name": "Alice", "age": 30} kv.close() ``` -------------------------------- ### Use Namespace Keys (PickleDB) Source: https://github.com/patx/pickledb/blob/master/docs/index.html Shows how to use a colon-separated prefix to simulate namespaces for keys. A helper function is provided to retrieve all keys starting with a given prefix. ```python db.set("user:1", {"name": "Alice"}) db.set("user:2", {"name": "Bob"}) def keys_with_prefix(db, prefix): return [k for k in db.all() if k.startswith(prefix)] print(keys_with_prefix(db, "user:")) ``` -------------------------------- ### Get All Keys (Sync) Source: https://github.com/patx/pickledb/blob/master/docs/index.html Retrieves a list of all keys currently stored in the in-memory database. The order of keys is not guaranteed. ```python db.all() ``` -------------------------------- ### Get All Keys Source: https://github.com/patx/pickledb/blob/master/_autodocs/api-reference/pickledb.md Returns a list of all keys currently present in the database. The order of keys in the returned list is arbitrary. ```python db.set("a", 1) db.set("b", 2) db.all() # Returns ["a", "b"] (order may vary) ``` -------------------------------- ### get Source: https://github.com/patx/pickledb/blob/master/_autodocs/api-reference/pickledb.md Retrieves a value from the database by key. Returns a default value if the key is not found. Keys are converted to strings. ```APIDOC ## get ### Description Retrieves a value from the database by key. If the key doesn't exist, returns the `default` value. Keys are converted to strings. ### Method `get(key, default=None)` ### Parameters #### Path Parameters - **key** (any) - Required - Dictionary key. Converted to string. - **default** (any) - Optional - `None` - Value returned if key doesn't exist. ### Returns The value for the key, or `default` if not found. ### Example ```python db.set("color", "blue") db.get("color") # Returns "blue" db.get("missing") # Returns None db.get("missing", default="unknown") # Returns "unknown" ``` ``` -------------------------------- ### Basic Synchronous Usage of PickleDB Source: https://github.com/patx/pickledb/blob/master/_autodocs/REFERENCE.md Demonstrates creating, loading, setting, getting, listing, and removing data using the synchronous API of PickleDB. Remember to save changes to disk. ```python from pickledb import PickleDB # Create and load database db = PickleDB("mydata.json").load() # Store data db.set("name", "Alice") db.set("age", 30) db.set("tags", ["python", "data"]) # Retrieve data print(db.get("name")) # "Alice" print(db.get("missing", default="N/A")) # "N/A" # List all keys print(db.all()) # ["name", "age", "tags"] # Delete a key db.remove("tags") # Save to disk db.save() ``` -------------------------------- ### Asynchronous Database Operations Source: https://github.com/patx/pickledb/blob/master/docs/index.html Shows how to perform asynchronous database operations using `async`/`await` for loading, setting, getting, and saving. ```python import asyncio from pickledb import PickleDB async def main(): db = PickleDB("data.json") await db.load() await db.set("score", 42) value = await db.get("score") print(value) # → 42 await db.save() asyncio.run(main()) ``` -------------------------------- ### Get All Keys from SQLite (Sync) Source: https://github.com/patx/pickledb/blob/master/docs/index.html Retrieves a list of all keys stored in the SQLite table, sorted by key. ```python kv.all() ``` -------------------------------- ### Get All Keys from SQLite (Async) Source: https://github.com/patx/pickledb/blob/master/docs/index.html Asynchronously retrieves a list of all keys stored in the SQLite table, sorted by key. ```python await kv.all() ``` -------------------------------- ### Get Key from SQLite (Sync) Source: https://github.com/patx/pickledb/blob/master/docs/index.html Retrieves a value from the SQLite-backed store by key. If the key does not exist and no default is provided, a KeyError is raised. ```python kv.get(key) ``` ```python kv.get("missing", default=None) ``` -------------------------------- ### Handle Missing SQLite Dependency for PickleDBSQLite Source: https://github.com/patx/pickledb/blob/master/_autodocs/configuration.md Demonstrates how to catch the RuntimeError if the 'aiosqlite' dependency is not installed when attempting to instantiate PickleDBSQLite. ```python try: kv = PickleDBSQLite() except RuntimeError as e: print(e) # "PickleDBSQLite requires `aiosqlite`. Install it via..." ``` -------------------------------- ### Synchronous Database Operations Source: https://github.com/patx/pickledb/blob/master/docs/index.html Demonstrates basic synchronous operations like loading, setting values, getting values, and saving to a JSON file. ```python from pickledb import PickleDB # Bind to a JSON file; no I/O yet db = PickleDB("data.json") db.load() db.set("username", "alice") db.set("theme", { "color": "blue", "font": "sans-serif" }) print(db.get("username")) # → "alice" db.save() # atomically write to disk ``` -------------------------------- ### Get All Keys (Async) Source: https://github.com/patx/pickledb/blob/master/docs/index.html Asynchronously retrieves a list of all keys currently stored in the in-memory database. The order of keys is not guaranteed. ```python await db.all() ``` -------------------------------- ### Get Key from SQLite (Async) Source: https://github.com/patx/pickledb/blob/master/docs/index.html Asynchronously retrieves a value from the SQLite-backed store by key. If the key does not exist and no default is provided, a KeyError is raised. ```python await kv.get(key) ``` -------------------------------- ### Get Value by Key (Sync) Source: https://github.com/patx/pickledb/blob/master/_autodocs/api-reference/pickledb-sqlite.md Retrieves a value by key. Returns a default value if the key is not found and a default is provided. Otherwise, raises KeyError. ```python kv.set("name", "Alice") # Sync: with default print(kv.get("name")) # "Alice" print(kv.get("missing", default="unknown")) # "unknown" # Sync: without default (raises on missing) try: kv.get("missing") # Raises KeyError except KeyError: print("Not found") ``` -------------------------------- ### PickleDB JSON Format Example Source: https://github.com/patx/pickledb/blob/master/_autodocs/REFERENCE.md Illustrates the structure of data stored in the PickleDB JSON format. Keys are strings and values can be any valid JSON type. ```json { "key1": "value1", "key2": 42, "key3": ["a", "b", "c"], "key4": {"nested": "object"} } ``` -------------------------------- ### Handling Missing Keys in PickleDBSQLite (with default) Source: https://github.com/patx/pickledb/blob/master/_autodocs/REFERENCE.md In PickleDBSQLite, you can provide a default value to the get() method to avoid KeyErrors when a key is missing. ```python # PickleDBSQLite: Use default to avoid KeyError value = kv.get("missing", default="N/A") # "N/A" ``` -------------------------------- ### Get Value by Key Source: https://github.com/patx/pickledb/blob/master/_autodocs/api-reference/pickledb.md Retrieves a value from the database by key. Keys are converted to strings. Returns a default value if the key is not found. ```python db.set("color", "blue") db.get("color") # Returns "blue" db.get("missing") # Returns None db.get("missing", default="unknown") # Returns "unknown" ``` -------------------------------- ### Get Value by Key (Async) Source: https://github.com/patx/pickledb/blob/master/_autodocs/api-reference/pickledb-sqlite.md Asynchronously retrieves a value by key. Requires await. Returns a default value if the key is not found and a default is provided. ```python # Async value = await kv.get("name") ``` -------------------------------- ### Get Key (Sync) Source: https://github.com/patx/pickledb/blob/master/docs/index.html Retrieves the value associated with a key from the in-memory database. If the key does not exist, it returns the specified default value (or None if no default is provided). ```python db.get("name") ``` ```python db.get("name", default="guest") ``` -------------------------------- ### get Source: https://github.com/patx/pickledb/blob/master/_autodocs/api-reference/pickledb-sqlite.md Retrieves a value from the database by key. If the key doesn't exist, it either raises a `KeyError` or returns a default value. Values are JSON-deserialized upon retrieval. In async code, returns a coroutine. ```APIDOC ## get ### Description Retrieves a value from the database by key. If the key doesn't exist, it either raises `KeyError` (if `default` is `MISSING`) or returns the `default` value. Values are JSON-deserialized upon retrieval. ### Method Signature ```python def get(self, key: str, default: Any = MISSING) -> Any ``` ### Parameters #### Path Parameters - **key** (str) - Required - Key to retrieve. - **default** (Any) - Optional - Value returned if key doesn't exist. If `MISSING` (sentinel), raises `KeyError`. ### Returns - **Any** - The deserialized value, or `default` if key not found ### Throws - **KeyError** - If key doesn't exist and `default` is `MISSING` ### Example ```python kv.set("name", "Alice") # Sync: with default print(kv.get("name")) # "Alice" print(kv.get("missing", default="unknown")) # "unknown" # Sync: without default (raises on missing) try: kv.get("missing") # Raises KeyError except KeyError: print("Not found") # Async value = await kv.get("name") ``` ``` -------------------------------- ### Basic Key-Value Operations Source: https://github.com/patx/pickledb/blob/master/README.md Demonstrates basic operations like loading the database, setting a key-value pair, and retrieving a value. Ensure 'example.json' is accessible or will be created. ```python from pickledb import PickleDB db = PickleDB("example.json").load() db.set("key", "value") db.get("key") # return "value" ``` -------------------------------- ### Configure PickleDB and PickleDBSQLite from Environment Variables Source: https://github.com/patx/pickledb/blob/master/_autodocs/configuration.md Set up PickleDB and PickleDBSQLite instances using paths and table names read from environment variables, with fallback defaults. ```python import os from pickledb import PickleDB # Read from environment db_path = os.getenv("PICKLEDB_PATH", "pickledb.json") sqlite_path = os.getenv("SQLITE_PATH", "pickledb.sqlite3") table_name = os.getenv("TABLE_NAME", "kv") db = PickleDB(db_path) kv = PickleDBSQLite(sqlite_path, table_name=table_name) ``` -------------------------------- ### Initialize PickleDB (JSON and SQLite) Source: https://github.com/patx/pickledb/blob/master/_autodocs/INDEX.md Demonstrates how to initialize a database connection for both JSON-based (PickleDB) and SQLite-based (PickleDBSQLite) storage. ```python # JSON-based (PickleDB) from pickledb import PickleDB db = PickleDB("data.json").load() ``` ```python # SQLite-based (PickleDBSQLite) from pickledb import PickleDBSQLite kv = PickleDBSQLite("store.sqlite3") ``` -------------------------------- ### Load and Use PickleDB Source: https://github.com/patx/pickledb/blob/master/_autodocs/README.md Demonstrates how to load a PickleDB database from a JSON file, set a key-value pair, retrieve the value, and save the changes. ```python from pickledb import PickleDB db = PickleDB("data.json").load() db.set("key", "value") print(db.get("key")) db.save() ``` -------------------------------- ### Initialize PickleDB with JSON Path Source: https://github.com/patx/pickledb/blob/master/_autodocs/configuration.md Instantiate PickleDB by providing the path to the JSON database file. ```python db = PickleDB("/path/to/db.json") ``` -------------------------------- ### __init__ Source: https://github.com/patx/pickledb/blob/master/_autodocs/api-reference/pickledb.md Initializes a new PickleDB instance. It sets up the in-memory database and an async lock for thread-safe operations. Data is not loaded from disk automatically; the `load()` method must be called separately. ```APIDOC ## `__init__` Constructor ### Description Initializes a new PickleDB instance with an empty in-memory dictionary and an async lock for thread-safe operations. Does not load data from disk — you must call `load()` separately. ### Parameters #### Path Parameters - **location** (str) - Required - File path where the JSON database will be stored. Supports `~` expansion for home directory. ### Example ```python from pickledb import PickleDB db = PickleDB("mydata.json") db.load() db.set("name", "Alice") db.save() ``` ``` -------------------------------- ### Load PickleDB Configuration from Environment Source: https://github.com/patx/pickledb/blob/master/_autodocs/configuration.md Manage PickleDB configuration programmatically by loading the database path from environment variables or using a default. ```python import os import json # Load config from environment db_path = os.getenv("DB_PATH", "default.json") db = PickleDB(db_path) ``` -------------------------------- ### Initialize and Use PickleDB Source: https://github.com/patx/pickledb/blob/master/_autodocs/api-reference/pickledb.md Initializes a PickleDB instance, loads data, sets a key-value pair, and saves the changes to disk. Ensure you call load() before performing operations and save() to persist data. ```python from pickledb import PickleDB db = PickleDB("mydata.json") db.load() db.set("name", "Alice") db.save() ``` -------------------------------- ### Initialize and Set Data Source: https://github.com/patx/pickledb/blob/master/docs/index.html Demonstrates how to initialize pickleDB and set a key-value pair. This is a fundamental operation for storing data. ```python from pickleDB import PickleDB db = PickleDB('my_database.json', False) db.set('name', 'Alice') db.set('age', 30) db.dump() print(db.get('name')) print(db.get('age')) ``` -------------------------------- ### Valid SQLite Table Names Source: https://github.com/patx/pickledb/blob/master/_autodocs/errors.md Examples of valid table names for PickleDBSQLite, adhering to the regex `^[A-Za-z_][A-Za-z0-9_]*$`. ```Python # Valid names kv = PickleDBSQLite("app.db", table_name="users") kv = PickleDBSQLite("app.db", table_name="user_sessions") kv = PickleDBSQLite("app.db", table_name="_private") kv = PickleDBSQLite("app.db", table_name="table123") ``` -------------------------------- ### List All Keys in PickleDB Source: https://github.com/patx/pickledb/blob/master/_autodocs/INDEX.md Demonstrates how to retrieve a list of all keys currently stored in the database. ```python keys = db.all() # Returns list[str] ``` -------------------------------- ### Load Existing Database Source: https://github.com/patx/pickledb/blob/master/docs/index.html Shows how to load an existing pickleDB database from a JSON file. Ensure the file exists before attempting to load. ```python from pickleDB import PickleDB db = PickleDB('my_database.json', True) print(db.get('name')) print(db.get('age')) ``` -------------------------------- ### Basic Usage of PickleDBSQLite Source: https://github.com/patx/pickledb/blob/master/_autodocs/REFERENCE.md Demonstrates creating a SQLite-based database, setting values with auto-generated or explicit keys, retrieving data, and performing remove/purge operations. Ensure to close the connection. ```python from pickledb import PickleDBSQLite # Create SQLite database kv = PickleDBSQLite("store.sqlite3") # Set with auto-generated UUID key key = kv.set(None, {"user": "Alice"}) print(key) # e.g., "550e8400-e29b-41d4-a716-446655440000" # Set with explicit key kv.set("config", {"debug": True}) # Get values print(kv.get("config")) # {"debug": True} # List all keys print(kv.all()) # ["550e8400-...", "config"] # Remove and purge kv.remove("config") kv.purge() # Delete all kv.close() ``` -------------------------------- ### Delete Keys and Purge Database with PickleDB Source: https://github.com/patx/pickledb/blob/master/_autodocs/INDEX.md Illustrates how to remove a specific key and how to delete all keys from the database. ```python was_present = db.remove("key") # True/False db.purge() # Delete all keys ``` -------------------------------- ### Handle Missing Keys in PickleDB and PickleDBSQLite Source: https://github.com/patx/pickledb/blob/master/_autodocs/INDEX.md Shows how to handle cases where a requested key does not exist, using a default value for PickleDB and a try-except block for PickleDBSQLite. ```python # PickleDB: Returns None or default value = db.get("missing", default="N/A") ``` ```python # PickleDBSQLite: Raises KeyError unless default provided try: value = kv.get("missing") except KeyError: value = "N/A" ``` -------------------------------- ### Handling Missing Keys in PickleDB Source: https://github.com/patx/pickledb/blob/master/_autodocs/REFERENCE.md In PickleDB, the get() method returns None or a specified default value when a key is missing. This prevents KeyErrors. ```python # PickleDB: Always returns None or default value = db.get("missing", default="N/A") # "N/A" ``` -------------------------------- ### Store and Retrieve Data with PickleDB Source: https://github.com/patx/pickledb/blob/master/_autodocs/INDEX.md Shows how to set a key-value pair and retrieve a value associated with a key in a PickleDB instance. ```python db.set("key", "value") value = db.get("key", default=None) ``` -------------------------------- ### Store and Update List (PickleDB) Source: https://github.com/patx/pickledb/blob/master/docs/index.html Demonstrates storing a list and then appending an item to it. The modified list is then re-stored. ```python db.set("tasks", ["write", "test", "deploy"]) tasks = db.get("tasks", []) tasks.append("celebrate") db.set("tasks", tasks) print(db.get("tasks")) ``` -------------------------------- ### Basic TTL Pattern in Python Source: https://github.com/patx/pickledb/blob/master/docs/index.html Demonstrates how to implement a Time-To-Live (TTL) pattern for data stored in PickleDB. This involves setting a key with an expiration timestamp and retrieving it only if it's still fresh. Use this for temporary data storage like sessions. ```python import time def set_with_ttl(db, key, value, ttl_seconds): db.set(key, { "value": value, "expires_at": time.time() + ttl_seconds, }) def get_if_fresh(db, key): data = db.get(key) if not data: return None if time.time() < data.get("expires_at", 0): return data["value"] db.remove(key) return None set_with_ttl(db, "session", "active", ttl_seconds=5) time.sleep(3) print(get_if_fresh(db, "session")) # 'active' time.sleep(3) print(get_if_fresh(db, "session")) # None ``` -------------------------------- ### Persist Data to Disk with PickleDB Source: https://github.com/patx/pickledb/blob/master/_autodocs/INDEX.md Illustrates how to explicitly save changes to disk for PickleDB. PickleDBSQLite persists automatically. ```python db.save() # PickleDB # PickleDBSQLite automatically persists on each operation ``` -------------------------------- ### Initialize PickleDBSQLite with Table Name Source: https://github.com/patx/pickledb/blob/master/_autodocs/configuration.md Instantiate PickleDBSQLite, specifying the SQLite database file and an optional table name. ```python kv = PickleDBSQLite("database.sqlite3", table_name="my_table") ``` -------------------------------- ### Correctly Awaiting Async PickleDB Methods Source: https://github.com/patx/pickledb/blob/master/_autodocs/errors.md Demonstrates the correct way to use async methods with PickleDB in an async context. Always 'await' async operations and ensure 'load' and 'save' are awaited. ```python async def good_example(): db = PickleDB("db.json") await db.load() await db.set("key", "value") await db.save() ``` -------------------------------- ### MISSING Constant for Default Values Source: https://github.com/patx/pickledb/blob/master/_autodocs/api-reference/utilities.md A sentinel object used as a default for get operations, signaling that a KeyError should be raised if the key is not found and no explicit default is provided. ```python from pickledb import PickleDBSQLite, MISSING kv = PickleDBSQLite() kv.set("exists", "value") # Using get with explicit default result = kv.get("missing", default="fallback") # Returns "fallback" # Using get with MISSING (raises KeyError) try: result = kv.get("missing", default=MISSING) # Raises KeyError except KeyError: print("Key not found") # get without explicit default (MISSING is implicit) try: result = kv.get("missing") # Raises KeyError except KeyError: print("Key not found") ``` -------------------------------- ### Initialize PickleDBSQLite with Defaults Source: https://github.com/patx/pickledb/blob/master/_autodocs/configuration.md Initialize PickleDBSQLite without arguments to use the default SQLite database file name (`pickledb.sqlite3`) and table name (`kv`). ```python kv = PickleDBSQLite() ``` -------------------------------- ### Get Key (Async) Source: https://github.com/patx/pickledb/blob/master/docs/index.html Asynchronously retrieves the value associated with a key from the in-memory database. If the key does not exist, it returns the specified default value (or None if no default is provided). ```python await db.get("name") ``` -------------------------------- ### all Source: https://github.com/patx/pickledb/blob/master/_autodocs/api-reference/pickledb.md Returns a list of all keys currently stored in the database as strings. The order of keys is arbitrary. ```APIDOC ## all ### Description Returns a list of all keys in the database as strings. Order is arbitrary. ### Method `all()` ### Parameters None ### Returns `list[str]` — All keys currently in the database. ### Example ```python db.set("a", 1) db.set("b", 2) db.all() # Returns ["a", "b"] (order may vary) ``` ``` -------------------------------- ### Handling Missing Keys in PickleDBSQLite (with try-except) Source: https://github.com/patx/pickledb/blob/master/_autodocs/REFERENCE.md In PickleDBSQLite, attempting to get a missing key without a default value raises a KeyError. Use a try-except block to handle this. ```python # PickleDBSQLite: Raises KeyError unless default provided try: value = kv.get("missing") # Raises KeyError except KeyError: value = "N/A" ``` -------------------------------- ### all Source: https://github.com/patx/pickledb/blob/master/_autodocs/api-reference/pickledb-sqlite.md Retrieves all keys from the database in alphabetical order. Returns an empty list if the table is empty. In async code, returns a coroutine. ```APIDOC ## all ### Description Retrieves all keys from the database in alphabetical order. Returns an empty list if the table is empty. ### Method Signature ```python def all(self) -> list[str] ``` ### Returns - **list[str]** - All keys in the database, ordered alphabetically ### Example ```python kv.set("a", 1) kv.set("b", 2) kv.set("c", 3) # Sync keys = kv.all() # ["a", "b", "c"] # Async keys = await kv.all() ``` ``` -------------------------------- ### Asynchronous Context Manager Usage Source: https://github.com/patx/pickledb/blob/master/docs/index.html Demonstrates using an asynchronous context manager for automatic loading and saving in async functions. ```python import asyncio from pickledb import PickleDB async def main(): async with PickleDB("data.json") as db: # On enter: await db.load() await db.set("foo", "bar") await db.set("hello", "world") # On exit: await db.save() asyncio.run(main()) ``` -------------------------------- ### PickleDBSQLite get() Source: https://github.com/patx/pickledb/blob/master/docs/index.html Retrieves a value from the SQLite table by its key. The value is deserialized from orjson. If the key does not exist and no default is provided, a KeyError is raised. Supports both synchronous and asynchronous operations. ```APIDOC ## PickleDBSQLite get(key: str, default: Any = MISSING) -> Any ### Description Retrieves a value from the SQLite table by its key. The value is deserialized from orjson. If the key does not exist and no default is provided, a KeyError is raised. Supports both synchronous and asynchronous operations. ### Method Supports both sync and async operations. ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - **key** (str) - The key of the value to retrieve. - **default** (Any) - Optional. The default value to return if the key does not exist. If not provided and the key is missing, a `KeyError` is raised. ### Request Example ```python # Sync value = kv.get("my_key") default_value = kv.get("missing_key", default=None) # Async value = await kv.get("my_key") default_value = await kv.get("missing_key", default=None) ``` ### Response #### Success Response (Any) - Returns the deserialized value associated with the key, or the specified default value if the key is not found. #### Response Example ```json {"foo": "bar"} ``` #### Error Response (KeyError) - Raised if the key does not exist and no default value is provided. ``` -------------------------------- ### PickleDB get() Source: https://github.com/patx/pickledb/blob/master/docs/index.html Retrieves the value associated with a given key from the in-memory database. If the key does not exist, it returns a specified default value (or None if no default is provided). Supports both synchronous and asynchronous operations. ```APIDOC ## PickleDB get(key: Any, default: Any | None = None) ### Description Retrieves the value associated with a given key from the in-memory database. If the key does not exist, it returns a specified default value (or None if no default is provided). Supports both synchronous and asynchronous operations. ### Method Supports both sync and async operations. ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - **key** (Any) - The key whose value needs to be retrieved. - **default** (Any | None) - Optional. The default value to return if the key does not exist. Defaults to None. ### Request Example ```python # Sync value = db.get("name") default_value = db.get("age", default=0) # Async value = await db.get("name") default_value = await db.get("age", default=0) ``` ### Response #### Success Response (Any | None) - Returns the stored value associated with the key, or the specified default value if the key is not found. #### Response Example ```json "alice" ``` ``` -------------------------------- ### Initialize PickleDBSQLite with Custom Path and Table Source: https://github.com/patx/pickledb/blob/master/_autodocs/configuration.md Specify a custom path for the SQLite database file and a custom table name. The table name must adhere to SQL identifier rules. ```python kv = PickleDBSQLite("app.db", table_name="store") ``` -------------------------------- ### PickleDBSQLite Constructor Source: https://github.com/patx/pickledb/blob/master/_autodocs/api-reference/pickledb-sqlite.md Initializes a new PickleDBSQLite instance with a connection to a SQLite database. Automatically creates the key-value table if it doesn't exist. Uses sqlite3.connect() with check_same_thread=False to allow usage across threads. ```APIDOC ## PickleDBSQLite Constructor ### Description Initializes a new PickleDBSQLite instance with a connection to a SQLite database. Automatically creates the key-value table if it doesn't exist. Uses `sqlite3.connect()` with `check_same_thread=False` to allow usage across threads. ### Signature ```python def __init__( self, sqlite_path: str = "pickledb.sqlite3", table_name: str = "kv", ) -> None ``` ### Parameters #### Path Parameters - **sqlite_path** (str) - Optional - Path to the SQLite database file. Defaults to `"pickledb.sqlite3"`. - **table_name** (str) - Optional - Name of the key-value table. Must match `[A-Za-z_][A-Za-z0-9_]*` (valid SQL identifier). Defaults to `"kv"`. ### Returns - `PickleDBSQLite` instance ### Throws - `ValueError` if `table_name` is invalid (doesn't match regex or isn't a string) ### Example ```python from pickledb import PickleDBSQLite kv = PickleDBSQLite("store.sqlite3") kv.set("user:1", {"name": "Alice", "age": 30}) print(kv.get("user:1")) # {"name": "Alice", "age": 30} kv.close() ``` ``` -------------------------------- ### Initialize Multiple PickleDBSQLite Instances Source: https://github.com/patx/pickledb/blob/master/_autodocs/configuration.md Use the same SQLite database file with different table names by providing distinct `table_name` arguments to multiple PickleDBSQLite instances. ```python kv1 = PickleDBSQLite("app.db", table_name="cache") kv2 = PickleDBSQLite("app.db", table_name="sessions") ``` -------------------------------- ### Set and Save Data in PickleDB (JSON) Source: https://github.com/patx/pickledb/blob/master/_autodocs/configuration.md Shows how to set a nested dictionary value and then save it to a JSON file using PickleDB. ```python db.set("data", {"nested": [1, 2, 3]}) db.save() # Writes JSON file ``` -------------------------------- ### Initialize PickleDB with Location Source: https://github.com/patx/pickledb/blob/master/_autodocs/configuration.md Use the `location` parameter to specify the file path for JSON database persistence. Supports absolute paths, home-relative paths (using `~`), and current directory paths. ```python db = PickleDB("/var/lib/app/data.json") ``` ```python db = PickleDB("~/app_data/store.json") ``` ```python db = PickleDB("./local.json") ``` -------------------------------- ### load Source: https://github.com/patx/pickledb/blob/master/_autodocs/api-reference/pickledb.md Loads JSON database from disk into memory. Initializes with an empty dictionary if the file doesn't exist or is empty. Supports both synchronous and asynchronous usage. ```APIDOC ## load ### Description Loads JSON database from disk into memory. If the file doesn't exist or is empty (0 bytes), initializes with an empty dictionary. Uses `aiofiles` for non-blocking I/O. ### Method `load()` ### Parameters None ### Returns `bool` - Indicates success or failure of the load operation. ### Throws/Rejects - `IOError` if file cannot be read - `ValueError` if file contains invalid JSON ### Example ```python # Sync usage db = PickleDB("data.json") db.load() # Async usage db = PickleDB("data.json") await db.load() # Chaining db = PickleDB("data.json").load() ``` ``` -------------------------------- ### Listing and Iterating Keys in PickleDB Source: https://github.com/patx/pickledb/blob/master/_autodocs/REFERENCE.md Retrieve all keys from the database using the all() method and then iterate through them to access individual values. ```python # Get all keys keys = db.all() # ["key1", "key2", ...] ``` ```python # Iterate and retrieve for key in db.all(): value = db.get(key) print(f"{key}: {value}") ``` -------------------------------- ### Auto-Generate Keys in PickleDBSQLite Source: https://github.com/patx/pickledb/blob/master/_autodocs/INDEX.md Demonstrates how to set a value without providing a key, allowing PickleDBSQLite to auto-generate a UUID for the key. ```python key = kv.set(None, {"data": "value"}) # UUID generated ``` -------------------------------- ### PickleDB Class Methods Source: https://github.com/patx/pickledb/blob/master/_autodocs/README.md Provides documentation for the public methods of the PickleDB class, which offers a JSON-based in-memory key-value store with disk persistence. ```APIDOC ## PickleDB ### Description Represents a JSON-based in-memory key-value store with disk persistence capabilities. ### Methods #### `__init__(location)` - **Description**: Constructor for the PickleDB class. - **Parameters**: - `location` (str) - The path for storing the database file. #### `load()` - **Description**: Loads data from the disk into the in-memory store. #### `save()` - **Description**: Saves the current in-memory data to disk atomically. #### `set(key, value)` - **Description**: Sets a key-value pair in the store. - **Parameters**: - `key` (str) - The key to set. - `value` (Any) - The value to associate with the key. - **Returns**: bool - True if the operation was successful, False otherwise. #### `get(key, default=None)` - **Description**: Retrieves the value associated with a given key. - **Parameters**: - `key` (str) - The key to retrieve. - `default` (Any) - The default value to return if the key is not found (defaults to None). - **Returns**: Any - The value associated with the key, or the default value if not found. #### `remove(key)` - **Description**: Removes a key-value pair from the store. - **Parameters**: - `key` (str) - The key to remove. - **Returns**: bool - True if the key was found and removed, False otherwise. #### `all()` - **Description**: Retrieves all keys currently stored. - **Returns**: list[str] - A list of all keys. #### `purge()` - **Description**: Removes all key-value pairs from the store. - **Returns**: bool - True if the purge operation was successful. ``` -------------------------------- ### Handling KeyError in PickleDBSQLite.get() Source: https://github.com/patx/pickledb/blob/master/_autodocs/errors.md Demonstrates how to catch KeyError when accessing a non-existent key in PickleDBSQLite without a default value. It also shows how to use the default argument to prevent the exception. ```python from pickledb import PickleDBSQLite kv = PickleDBSQLite() v.set("exists", "value") # Will raise KeyError try: result = kv.get("missing") except KeyError as e: print(f"Key not found: {e}") # Avoid KeyError with a default result = kv.get("missing", default="fallback") # Returns "fallback" ``` -------------------------------- ### Check Key Existence Source: https://github.com/patx/pickledb/blob/master/docs/index.html Shows how to check if a specific key exists in the database. This is helpful for preventing errors when accessing potentially non-existent keys. ```python from pickleDB import PickleDB db = PickleDB('my_database.json', False) db.set('exists_key', 'exists_value') db.dump() print(db.exists('exists_key')) print(db.exists('non_existent_key')) ``` -------------------------------- ### In-Memory Persistence with PickleDB Source: https://github.com/patx/pickledb/blob/master/_autodocs/REFERENCE.md Illustrates the workflow for loading data from a JSON file into memory, modifying it, and then saving the changes back to disk. Unsaved in-memory changes are lost on program crash. ```python db = PickleDB("data.json") db.load() # Reads JSON file into memory db.set("key", "value") # Updates in-memory dict (NOT disk) db.save() # Writes memory to disk ``` -------------------------------- ### Utility Functions Source: https://github.com/patx/pickledb/blob/master/_autodocs/MANIFEST.txt Reference for utility functions and decorators provided by the PickleDB library. ```APIDOC ## in_async() ### Description Detects if the current execution context is within an asyncio event loop. ### Method in_async ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```python if in_async(): print('Running in async mode') else: print('Running in sync mode') ``` ### Response #### Success Response (200) - **is_async** (bool) - True if running in an asyncio event loop, False otherwise. #### Response Example ```python print(True) # or print(False) ``` ## @dualmethod decorator ### Description A decorator that allows a method to be called from both synchronous and asynchronous contexts, automatically handling the event loop. ### Method @dualmethod ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```python @dualmethod def my_dual_method(self, arg1): # Method implementation pass ``` ### Response #### Success Response (200) - **None** - The decorator modifies the method in place. #### Response Example ```python # No direct response, the decorated method is ready for dual use. ``` ## MISSING (sentinel) ### Description A sentinel constant used to indicate a missing value, often as a default for parameters. ### Method MISSING ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```python def get_value(key, default=MISSING): # ... pass ``` ### Response #### Success Response (200) - **MISSING** (object) - The sentinel object. #### Response Example ```python print(MISSING) ``` ``` -------------------------------- ### Store and Update Dictionary (PickleDB) Source: https://github.com/patx/pickledb/blob/master/docs/index.html Demonstrates storing a dictionary and then updating a value within it. The modified dictionary is then re-stored. ```python # Store a dictionary db.set("user", {"name": "Alice", "age": 30}) # Update it user = db.get("user") user["age"] += 1 db.set("user", user) print(db.get("user")) ``` -------------------------------- ### Configure SQLite Table Name in PickleDBSQLite Source: https://github.com/patx/pickledb/blob/master/_autodocs/INDEX.md Shows how to specify a custom table name when initializing a PickleDBSQLite database. ```python kv = PickleDBSQLite("db.sqlite3", table_name="custom_table") ``` -------------------------------- ### Initialize SQLite Connection Source: https://github.com/patx/pickledb/blob/master/_autodocs/types.md Initializes the SQLite connection for PickleDBSQLite. Allows usage from different threads but concurrent access is not recommended. ```python self._conn = sqlite3.connect(self.sqlite_path, check_same_thread=False) ``` -------------------------------- ### Clear Database Source: https://github.com/patx/pickledb/blob/master/docs/index.html Shows how to remove all key-value pairs from the database, effectively resetting it. Use with caution as all data will be lost. ```python from pickleDB import PickleDB db = PickleDB('my_database.json', False) db.set('key1', 'value1') db.set('key2', 'value2') print(db.getAllKeys()) db.empty() print(db.getAllKeys()) db.dump() ``` -------------------------------- ### In-Memory Data Persistence Source: https://github.com/patx/pickledb/blob/master/_autodocs/INDEX.md Illustrates the in-memory nature of PickleDB data and how to explicitly persist it to disk. Use `save()` to write data and `load()` to read it. ```python db.set("key", "value") # Memory only db.save() # Write to disk db.load() # Read from disk ``` -------------------------------- ### PickleDB all() Source: https://github.com/patx/pickledb/blob/master/docs/index.html Retrieves a list of all keys currently stored in the in-memory database. The order of keys in the returned list is not guaranteed. Supports both synchronous and asynchronous operations. ```APIDOC ## PickleDB all() -> list[str] ### Description Retrieves a list of all keys currently stored in the in-memory database. The order of keys in the returned list is not guaranteed. Supports both synchronous and asynchronous operations. ### Method Supports both sync and async operations. ### Parameters None ### Request Example ```python # Sync keys = db.all() # Async keys = await db.all() ``` ### Response #### Success Response (list[str]) - Returns a list of strings, where each string is a key present in the database. #### Response Example ```json ["name", "user:1", "user:2"] ``` ``` -------------------------------- ### PickleDBSQLite Class Methods Source: https://github.com/patx/pickledb/blob/master/_autodocs/README.md Provides documentation for the public methods of the PickleDBSQLite class, which uses an SQLite database for storage. ```APIDOC ## PickleDBSQLite ### Description Represents an in-memory key-value store backed by an SQLite database, offering features like auto-generated keys and custom table names. ### Methods #### `__init__(sqlite_path, table_name)` - **Description**: Constructor for the PickleDBSQLite class with validation. - **Parameters**: - `sqlite_path` (str) - The path to the SQLite database file. - `table_name` (str) - The name of the table to use within the database. #### `set(key, value)` - **Description**: Sets a key-value pair in the SQLite store. If key is None, an auto-generated key is used. - **Parameters**: - `key` (str | None) - The key to set, or None for an auto-generated key. - `value` (Any) - The value to associate with the key. - **Returns**: str - The key that was used (either provided or auto-generated). #### `get(key, default=MISSING)` - **Description**: Retrieves the value associated with a given key from the SQLite store. - **Parameters**: - `key` (str) - The key to retrieve. - `default` (Any) - The default value to return if the key is not found (defaults to a sentinel MISSING value). - **Returns**: Any - The value associated with the key, or the default value if not found. #### `remove(key)` - **Description**: Removes a key-value pair from the SQLite store. - **Parameters**: - `key` (str) - The key to remove. - **Returns**: bool - True if the key was found and removed, False otherwise. #### `all()` - **Description**: Retrieves all keys currently stored in the SQLite table. - **Returns**: list[str] - A list of all keys. #### `purge()` - **Description**: Removes all key-value pairs from the SQLite store. - **Returns**: bool - True if the purge operation was successful. #### `close()` - **Description**: Closes the connection to the SQLite database. ```