YORM (YAML Object-Relational Mapper)

1.6.2 · active · verified Thu Apr 16

YORM (YAML Object-Relational Mapper) is a Python library that provides automatic object-YAML mapping, allowing Python objects to be seamlessly persisted to and loaded from YAML files. It enables defining models with attributes that are automatically synchronized with a specified YAML file, supporting features like autosaving and schema validation. The current version is 1.6.2, and it has an active but irregular release cadence.

Common errors

Warnings

Install

Imports

Quickstart

This quickstart demonstrates how to define a YORM model, synchronize it with a temporary YAML file, create and update objects, and verify persistence. It uses `autosave=True` for automatic saving of changes.

import yorm
import os
import tempfile
import shutil

# Create a temporary directory for the YAML file
temp_dir = tempfile.mkdtemp()

try:
    # Define a model with autosave enabled at the class level
    @yorm.attr(autosave=True)
    class Person(yorm.Model):
        name = yorm.attr(type=str)
        email = yorm.attr(type=str, default='')

    # Synchronize the model with a YAML file in the temporary directory
    file_path = os.path.join(temp_dir, 'person.yaml')
    yorm.sync(Person, file_path)
    print(f"Synchronized Person model with: {file_path}")

    # Create a new person object. Due to autosave=True, it's saved automatically.
    print("\nCreating Bob...")
    bob = Person(name="Bob", email="bob@example.com")
    print(f"Bob created: {bob.name} ({bob.email})")

    # Update an attribute. The change is saved automatically.
    print("Updating Bob's email...")
    bob.email = "robert@example.com"
    print(f"Bob's email updated to: {bob.email}")

    # Fetch all persons (should be just Bob)
    print("\nFetching all persons...")
    persons = Person.all()
    for p in persons:
        print(f"Found: {p.name} ({p.email})")

    # Verify the update by reloading and checking
    if persons and persons[0].email == "robert@example.com":
        print("Update verified: Bob's email is now robert@example.com")
    else:
        print("Error: Bob's email not updated as expected.")

    # Delete all persons. This also gets persisted.
    print("\nDeleting all persons...")
    Person.all().clear()
    print(f"Persons remaining after clear: {len(Person.all())}")

finally:
    # Clean up the temporary directory
    shutil.rmtree(temp_dir)
    print(f"\nCleaned up temporary directory: {temp_dir}")

view raw JSON →