files

Files and cells over the gateway's contents and cells APIs

Jupyter servers, jupygate, and rustygate expose the /api/contents API for files, notebooks, and directories. Rustygate also adds /api/cells for editing cells inside live notebooks.

Use JupyAsyncFilesClient to address files by path. JupyAsyncCellsClient works with one notebook's cells. A kernel client bound to that notebook receives cell_ops change messages on its cells channel. apply_ops updates a local list of cells from those messages. Attach JmsgQueues if you want to read the broadcasts with get_jmsg.

import shutil, tempfile
from pathlib import Path
from fastcore.test import test_eq, expect_fail
from jupyasyncclient import start_gateway

The files client

Both clients inherit KernelApi's base URL, authentication, and HTTP transport. You can supply an HTTP client or let the transport create one for each request. Writes replace the addressed content; the last accepted edit wins.

source

JupyAsyncFilesClient

def JupyAsyncFilesClient(
    base_url, token=None, headers=None, timeout:int=30, http_client=None, verify:bool=True, spec=None
):

Files, notebooks, and directories over the standard Jupyter /api/contents API.

The file methods call standard /api/contents operations from jg_spec(). Gateway-specific options pass through fastspec's query_ and body_ arguments. fastspec leaves out a query argument whose value is None. HTTP errors propagate as APIError.

The helpers separate query parameters from body fields. For example, get(path) requests a model and put(path, type='directory') requests directory creation. patch passes its body through body_ because a rename has two paths: the URL's source path and the body's destination path.

Rustygate also supports overwrite=False, unique=True, URL copy sources, extract=True for archive extraction, and delete_source=True after extraction. An empty destination addresses the served root.

Use get to read a contents model, put to write, and post to copy through the contents API:

source

JupyAsyncFilesClient.post

async def post(
    path:str='', overwrite=None, unique=None, extract=None, delete_source=None, **kwargs
):

POST to the contents API; kwargs are its JSON body.

source

JupyAsyncFilesClient.put

async def put(
    path, overwrite=None, unique=None, parents=None, **kwargs
):

PUT to the contents API; kwargs are its JSON body.

source

JupyAsyncFilesClient.get

async def get(
    path:str='', **kwargs
):

The model at path; kwargs become query parameters, e.g. content=0, type='file', format='base64'.

For patch, pass the source path positionally. You can then use path= for the destination in the body. delete removes a file or an empty directory:

source

JupyAsyncFilesClient.delete

async def delete(
    path
):

Delete a file or an empty directory.

source

JupyAsyncFilesClient.patch

async def patch(
    path, /, **kwargs
):

PATCH with kwargs as the JSON body; path is positional-only, freeing the name for the body.

source

JupyAsyncFilesClient.listing

async def listing(
    path:str=''
):

The entries of directory path.

source

JupyAsyncFilesClient.read

async def read(
    path, type:str='file'
):

A file's contents: str for text, bytes for binary, or a notebook dict when type='notebook'.

source

JupyAsyncFilesClient.write

async def write(
    path, content, unique:bool=False, overwrite:bool=True
):

Write text, bytes, or a notebook dict and return the model. Rustygate adds unique and overwrite=False.

Let's start a local jupygate process with a temporary directory as its files root. All the following writes stay in that directory:

root = Path(tempfile.mkdtemp())
g = start_gateway(('jupygate', '--root', root))
fc = JupyAsyncFilesClient(g.url)
m = await fc.write('notes.txt', 'hello')
m
{ 'mtime': 1789266815.6835597,
  'name': 'notes.txt',
  'path': 'notes.txt',
  'size': 5,
  'type': 'file',
  'writable': True}

write returns the file model. Directory listings return those same stat fields without reading file contents:

test_eq(await fc.read('notes.txt'), 'hello')
entry = next(e for e in await fc.listing() if e['name']=='notes.txt')
test_eq(entry, m)
entry
{ 'mtime': 1789266815.6835597,
  'name': 'notes.txt',
  'path': 'notes.txt',
  'size': 5,
  'type': 'file',
  'writable': True}

Writing an existing file replaces its contents:

await fc.write('notes.txt', 'hello2')
test_eq(await fc.read('notes.txt'), 'hello2')
await fc.read('notes.txt')
'hello2'

On Rustygate, pass overwrite=False to require a new file (an existing path raises APIError with status 409):

await fc.write('fresh.txt', 'made', overwrite=False)
with expect_fail(APIError): await fc.write('fresh.txt', 'again', overwrite=False)
test_eq(await fc.read('fresh.txt'), 'made')

write base64-encodes bytes for transport. read returns text when the stored bytes are valid UTF-8, otherwise bytes. Here the binary data round-trips unchanged:

raw = bytes(range(256))
await fc.write('blob.bin', raw)
back = await fc.read('blob.bin')
test_eq(back, raw)
len(back)
256

mkdir, rename, and copy wrap the contents methods. Use parents=True to create missing directory ancestors.

A rename never overwrites an existing destination: it raises APIError with status 409. To replace a destination, delete it explicitly first:

source

JupyAsyncFilesClient.copy

async def copy(
    src, to:str='', unique:bool=False, overwrite:bool=True, extract=None, delete_source=None
):

Copy and return the new model. Rustygate adds unique and overwrite=False.

source

JupyAsyncFilesClient.rename

async def rename(
    path, to
):

Rename and return the new model. An existing destination raises APIError (409); it is never overwritten.

source

JupyAsyncFilesClient.mkdir

async def mkdir(
    path, parents:bool=False
):

Create directory path; parents creates missing ancestors like mkdir -p.

await fc.mkdir('sub')
await fc.mkdir('deep/a/b', parents=True)
await fc.copy('notes.txt', 'sub')
await fc.rename('sub/notes.txt', 'sub/renamed.txt')
with expect_fail(APIError): await fc.rename('sub/renamed.txt', 'notes.txt')
test_eq([e['name'] for e in await fc.listing('sub')], ['renamed.txt'])
await fc.copy('sub/renamed.txt')
test_eq(await fc.read('renamed.txt'), 'hello2')
await fc.delete('sub/renamed.txt')
await fc.delete('sub')
await fc.delete('blob.bin')
[e['name'] for e in await fc.listing()]
['deep', 'fresh.txt', 'notes.txt']

Pass a notebook dict to write to save a notebook via standard Jupyter JSON format, or post(type='notebook') to create an untitled notebook. read(path, type='notebook') returns the parsed notebook dict, while read(path) returns raw text:

nb_model = await fc.post('', type='notebook')
test_eq(nb_model['type'], 'notebook')
nb = dict(cells=[dict(cell_type='code', source='6*7', metadata={}, outputs=[], execution_count=None)], metadata={}, nbformat=4, nbformat_minor=5)
await fc.write('demo.ipynb', nb)
test_eq((await fc.read('demo.ipynb', type='notebook'))['cells'][0]['source'], '6*7')
assert isinstance(await fc.read('demo.ipynb'), str)
await fc.delete(nb_model['path'])
await fc.delete('demo.ipynb')
'notes_2.txt'

Use edit to change a JSON file. It reads the content, calls f to modify the parsed object in place, and writes the result once. Like any file write, it replaces intervening changes:

source

JupyAsyncFilesClient.edit

async def edit(
    path, f
):

Read the JSON file at path, apply f to the parsed object, and write it back.

await fc.write('cfg.json', json.dumps(dict(a=1)))
def _bump(o): o['a'] += 1
await fc.edit('cfg.json', _bump)
test_eq(json.loads(await fc.read('cfg.json'))['a'], 2)

The cells client

Construct JupyAsyncCellsClient with a notebook path or kernel_id and an explicit full Rustygate spec. The bundled public spec excludes the cells operations. Kernel-addressed cell operations follow the current binding through rename and restart. Inherited file methods still take explicit paths.

view returns the selected cells with their notebook path. Pass fields='meta' to include notebook metadata. cells returns the selected cell list.

await client[id] returns one cell; a tuple of ids returns a list.

source

JupyAsyncCellsClient

def JupyAsyncCellsClient(
    base_url, path=None, token=None, headers=None, timeout:int=30, http_client=None, verify:bool=True,
    kernel_id=None, *, spec
):

One notebook's cells over the gateway's cells API.

source

JupyAsyncCellsClient.cells

async def cells(
    ids=None, # Cell ids to keep: comma-separated str, or a list
    *,
    idx=None, # Cell positions to keep: comma-separated str, or a list of ints, 0-based, negative from the end; unions with `ids`
    section=None, # Cell id selecting a heading and its descendants; a non-heading selects itself
    ancestors=None, # Cell id whose enclosing headings to select, outermost first, excluding the cell itself
    before=None, # Cell id: select every cell before it, excluding it
    after=None, # Cell id: select every cell after it, excluding it
    q=None, # Keep only cells whose source matches this regex (multiline, smart-case)
    cell_type=None, # Keep only cells of this type: 'code', 'markdown', or 'raw'
    meta=None, # Keep only cells whose metadata contains this dict as a recursive subset; a None value means "key present"
    meta_not=None, # Drop cells whose metadata contains this dict as a recursive subset
    limit=None, # Keep at most this many cells after filtering
    max_tokens=None, # Then keep the newest cells whose approximate token counts total at most this many
    context=None, # Also return this many neighbours either side of each kept cell; `matched` in the result names the true matches
    fields=None, # Comma-separated cell fields; '*' includes attachments, 'meta' adds notebook metadata; None omits attachments
    compare=None, # Compare inputs with this Git ref; returns its resolved commit and computed cell change fields
):

The selected cells in document order.

source

JupyAsyncCellsClient.view

async def view(
    ids=None, # Cell ids to keep: comma-separated str, or a list
    idx=None, # Cell positions to keep: comma-separated str, or a list of ints, 0-based, negative from the end; unions with `ids`
    section=None, # Cell id selecting a heading and its descendants; a non-heading selects itself
    ancestors=None, # Cell id whose enclosing headings to select, outermost first, excluding the cell itself
    before=None, # Cell id: select every cell before it, excluding it
    after=None, # Cell id: select every cell after it, excluding it
    q=None, # Keep only cells whose source matches this regex (multiline, smart-case)
    cell_type=None, # Keep only cells of this type: 'code', 'markdown', or 'raw'
    meta=None, # Keep only cells whose metadata contains this dict as a recursive subset; a None value means "key present"
    meta_not=None, # Drop cells whose metadata contains this dict as a recursive subset
    limit=None, # Keep at most this many cells after filtering
    max_tokens=None, # Then keep the newest cells whose approximate token counts total at most this many
    context=None, # Also return this many neighbours either side of each kept cell; `matched` in the result names the true matches
    fields=None, # Comma-separated cell fields; '*' includes attachments, 'meta' adds notebook metadata; None omits attachments
    compare=None, # Compare inputs with this Git ref; returns its resolved commit and computed cell change fields
):

The selected cells with their notebook path, requested metadata, matched ids and comparison commit.

apply submits cell operations in order. command submits a semantic message operation, such as bookmark, split, or merge, with its fields as keyword arguments. Both return the added ids and use the client's path or kernel binding. _lookup implements bracket notation:

source

JupyAsyncCellsClient.command

async def command(
    op, **kwargs
):

Apply a semantic message command, returning ids of added cells.

source

JupyAsyncCellsClient.apply

async def apply(
    ops
):

Apply ops in order, returning ids of added cells.

Your application supplies base_url and a parsed full Rustygate specification as full_spec. For example, Solveit's rg_full_spec() reads its packaged full snapshot. Cells operations are not available from the bundled public specification:

nb = JupyAsyncCellsClient(base_url, 'analysis.ipynb', spec=full_spec)
await nb.cells(ids=['intro', 'result'], fields='id,source')
await nb.apply([dict(op='update', id='result', source='6*7')])
await nb.command('bookmark', id='intro', n=1)
['aaa1', 'bbb2']

Applying ops

apply_ops updates a list of cell dictionaries in place from broadcast operations. A client can keep its local view current without fetching the notebook after each change.

The gateway converts richer request operations, such as cell metadata merge, into add/update/delete broadcasts containing their results; move broadcasts carry IDs and placement and preserve the existing cell objects. Notebook-level meta leaves the cell list unchanged. Handle file-level rename and attachment events separately; passing them to this helper raises ValueError.

output_changed is event intent, not a cell field. Metadata/source snapshots preserve locally committed output; an intentional replacement applies even when its output list is empty. Execution counts remain ordinary canonical fields.

source

apply_ops

def apply_ops(
    cells, ops
):

Apply cell broadcast operations in order to cells in place and return that list.

Here we add a code cell before an existing cell, delete another cell, and turn the new cell into a Markdown heading. The type change removes its execution count and outputs:

view = [dict(id='aaa1', cell_type='code', source='1+1', metadata={}, outputs=[], execution_count=1),
    dict(id='bbb2', cell_type='markdown', source='# old', metadata={})]
ops = [dict(op='add', cell=dict(id='ccc3', cell_type='code', source='3'), before='aaa1'),
    dict(op='delete', id='bbb2'), dict(op='update', id='ccc3', cell_type='markdown', source='# Calculation')]
apply_ops(view, ops)
test_eq([c['id'] for c in view], ['ccc3', 'aaa1'])
assert 'outputs' not in view[0] and 'execution_count' not in view[0]
[(c['id'], c['cell_type']) for c in view]
[('ccc3', 'markdown'), ('aaa1', 'code'), ('97270c84', 'code')]

An add with an existing id updates that cell in place, ignoring the anchor. A missing anchor appends, and deleting a missing cell has no effect. Here the duplicate add turns ccc3 back into code with empty outputs and a null execution count:

ops = [dict(op='delete', id='missing'), dict(op='meta', metadata=dict(topic='calculation')),
    dict(op='add', cell=dict(id='ccc3', cell_type='code', source='3b'), after='missing'),
    dict(op='add', cell=dict(id='ddd4', source='4'), after='missing')]
apply_ops(view, ops)
test_eq([c['id'] for c in view], ['ccc3', 'aaa1', 'ddd4'])
test_eq((view[0]['outputs'], view[0]['execution_count']), ([], None))
test_eq(view[-1], dict(id='ddd4', source='4', cell_type='code', metadata={}, outputs=[], execution_count=None))
kept = view[-1]
apply_ops(view, [dict(op='move', ids=['ddd4', 'ccc3'], before='aaa1')])
test_eq([c['id'] for c in view], ['ddd4', 'ccc3', 'aaa1'])
assert view[0] is kept
kept['outputs'] = [dict(output_type='stream', name='stdout', text='live')]
apply_ops(view, [dict(op='update', id='ddd4', source='new', execution_count=2, outputs=[])])
test_eq((kept['outputs'][0]['text'], kept['execution_count']), ('live', 2))
apply_ops(view, [dict(op='update', id='ddd4', outputs=[], output_changed=True)])
test_eq(kept['outputs'], [])
assert 'output_changed' not in kept