This directory contains example scripts demonstrating how to use automerge-py with different transports.
Install automerge with WebSocket support:
pip install automerge[websocket]Or if you're developing:
pip install -e .[websocket]Runs a WebSocket server that shares Automerge documents with connected clients.
python examples/websocket_server.pyThe server will:
- Start on
ws://localhost:8080 - Create an initial document
- Accept connections from clients
- Show the number of active connections
Connects to a WebSocket server and syncs documents.
# First, start the server in another terminal:
python examples/websocket_server.py
# Then run the client:
python examples/websocket_client.pyThe client will:
- Connect to the server
- Create a new document
- Make changes that sync to the server
- Show the document URL
from automerge.repo import Repo, InMemoryStorage
from automerge.transports import WebSocketServer
# Create a repository
storage = InMemoryStorage()
repo = await Repo.load(storage)
# Start WebSocket server
async with repo:
async with WebSocketServer(repo, "localhost", 8080):
# Server is now running
await asyncio.sleep(3600)from automerge.repo import Repo, InMemoryStorage
from automerge.transports import WebSocketClientTransport
# Create a repository
storage = InMemoryStorage()
repo = await Repo.load(storage)
# Connect to server
async with repo:
transport = await WebSocketClientTransport.connect("ws://localhost:8080")
await repo.connect(transport)# Create a new document
handle = await repo.create()
# Initialize with content
with handle.change() as doc:
doc["title"] = "Hello"
doc["count"] = 0# Find a document by URL
handle = await repo.find(url)
if handle:
doc = handle.doc()
title = doc["title"]
print(f"Title: {title}")# Make changes to a document
with handle.change() as doc:
current = doc["count"]
doc["count"] = current + 1- Reading: Use
doc = handle.doc()for read-only access with Python dict-like syntax - Writing: Use
with handle.change() as doc:for mutations - Documents from
doc()are read-only and will raise errors on write attempts - Use
change()for all mutations
- Storage: The examples use
InMemoryStoragefor simplicity. For production, implement a persistent storage backend. - Ports: Make sure the ports used (8080, 8081) are available on your system.