Plyvel, a fast and feature-rich Python interface to LevelDB

1.5.1 · active · verified Sat Apr 11

Plyvel is a fast and feature-rich Python interface to LevelDB. It provides a comprehensive, high-performance Pythonic API that wraps most of the underlying LevelDB C++ API, leveraging Cython for speed. Key features include support for write batches, database snapshots, flexible iterators, and prefixed databases. The library is actively maintained, with version 1.5.1 released in January 2024, consistently adding support for new Python versions and ensuring compatibility with recent LevelDB releases.

Warnings

Install

Imports

Quickstart

This quickstart demonstrates opening a LevelDB database, performing basic put, get, and delete operations, and iterating over stored key-value pairs using `plyvel`. It highlights the recommended practice of using `plyvel.DB` as a context manager for automatic resource management and proper database closing.

import plyvel
import os
import shutil

# Define a path for the LevelDB database
db_path = '/tmp/testdb_plyvel_quickstart'

# Clean up any previous database at the path
if os.path.exists(db_path):
    shutil.rmtree(db_path)

try:
    # Open a new database, creating it if it doesn't exist
    # Using a context manager ensures the database is properly closed
    with plyvel.DB(db_path, create_if_missing=True) as db:
        print(f"Database opened at: {db_path}")

        # Put key-value pairs (keys and values must be bytes)
        db.put(b'name', b'Alice')
        db.put(b'age', b'30')
        db.put(b'city', b'New York')

        # Get a value
        name = db.get(b'name')
        if name:
            print(f"Name: {name.decode('utf-8')}")

        # Iterate over all key-value pairs
        print("\nAll entries:")
        for key, value in db:
            print(f"  {key.decode('utf-8')}: {value.decode('utf-8')}")

        # Delete a key
        db.delete(b'age')
        print("\nAfter deleting 'age':")

        # Verify deletion by iterating again
        for key, value in db:
            print(f"  {key.decode('utf-8')}: {value.decode('utf-8')}")

except Exception as e:
    print(f"An error occurred: {e}")
finally:
    # Ensure cleanup even if an error occurs
    if os.path.exists(db_path):
        shutil.rmtree(db_path)
        print(f"\nCleaned up database directory: {db_path}")

view raw JSON →