Working with Entries#
A LabArchives page contains entries for rich text, plain text, headers, file attachments, and widgets.
Accessing Entries#
A NotebookPage exposes entries, an Entries sequence.
page = notebook.traverse("Project A/Experiment 1/Results")
# Get the number of entries
print(len(page.entries))
# Iterate over entries
for entry in page.entries:
print(f"ID: {entry.id}, Type: {entry.content_type}")
# Access an entry by index
first_entry = page.entries[0]
Entry Metadata#
Every entry carries its LabArchives identifier and part type:
id and
content_type.
Entries also have three read-only fields:
created_at and
updated_at are
datetime objects parsed from the API’s ISO-8601 timestamps,
and version is an integer.
entry = page.entries[0]
print(f"{entry.id} ({entry.content_type})")
print(f"Version {entry.version}, last updated {entry.updated_at}")
Note
These fields are set on entries loaded from a page and on search results.
A field the response leaves out is None. They are not set on an entry
you have just made with
create(); reload the page to get
them.
Attachment entries add a caption,
and the Attachment returned by their
content carries filename,
mime_type, and its own
caption.
Searching Entries#
Use search() to search entries in a
notebook. It returns an EntrySearch, an iterable
of result pages. No API request is made until you iterate it or fetch a page.
Each page contains the same entry classes used by page.entries.
from labapi import TextEntry
for result_page in notebook.search('"brown rat"', page_size=100):
for entry in result_page.entries:
if isinstance(entry, TextEntry):
entry.content = entry.content.replace(
"brown rat",
"Rattus norvegicus",
)
Each result page is an EntrySearchPage, which
holds the matched entries and the result counts. To fetch one page without
iterating, call page():
search = notebook.search("Rattus norvegicus") # page_size defaults to 25
first_page = search.page(0) # page numbers are zero-based
print(f"{first_page.total_found} matching entries in the notebook")
print(f"{first_page.total_returned} entries on this page")
page() raises IndexError for
negative or out-of-range page numbers, and
search() raises ValueError if
page_size is not positive.
Entry Types#
Each entry type is a subclass of Entry.
Text-based Entries#
Text-based entries store their content as strings.
Rich Text Entry (
TextEntry): Formatted text, typically HTML. Content type:"text entry".Plain Text Entry (
PlainTextEntry): Unformatted text. Content type:"plain text entry".Header Entry (
HeaderEntry): A heading within a page. Content type:"heading".
# Accessing text content
text_entry = page.entries[0]
print(text_entry.content)
# Updating rich text content
text_entry.content = "<p>Updated <strong>rich text</strong> content</p>"
Attachment Entries#
The content of an AttachmentEntry is an Attachment object.
attachment_entry = page.entries[1]
attachment = attachment_entry.content
print(f"Filename: {attachment.filename}")
print(f"MIME Type: {attachment.mime_type}")
print(f"Caption: {attachment.caption}")
# Read the file data
data = attachment.read()
Warning
attachment.filename comes from LabArchives unchecked and may contain
path separators. Use pathlib.PureWindowsPath(attachment.filename).name
before saving a file under it.
Widget Entries#
Widget entries (WidgetEntry) embed interactive content or external applications. Like text entries, their content is represented as a string (often JSON or HTML).
Note
Widget entries are currently read-only in labapi.
entries wraps part types it does not
recognize as UnknownEntry and types it
recognizes but does not implement as
UnimplementedEntry, and emits a warning
for each.
Creating New Entries#
Call create() to add an entry to a page.
from labapi import TextEntry, HeaderEntry, PlainTextEntry
# Create a rich text entry (HTML is rendered in LabArchives)
page.entries.create(TextEntry, "<h2>New Section</h2><p>Some <em>formatted</em> content...</p>")
# Create a heading (displayed as a section label/divider)
page.entries.create(HeaderEntry, "Experiment Notes")
# Create a plain text entry (displayed literally)
page.entries.create(PlainTextEntry, "<h2>Raw instrument output</h2>")
Creating Attachments#
Create an Attachment object, then pass it to create().
from io import BytesIO
from labapi import Attachment, AttachmentEntry
# Create attachment from in-memory data
data = BytesIO(b"Hello, LabArchives!")
attachment = Attachment(data, "text/plain", "hello.txt", "A simple text file")
# Upload as a new entry
page.entries.create(AttachmentEntry, attachment)
You can also create an attachment directly from a file on disk:
from labapi import Attachment, AttachmentEntry
attachment = Attachment.from_file("data.csv")
page.entries.create(AttachmentEntry, attachment)
Attachment.from_file() accepts a filesystem path (string or Path) or a
random-access binary file object.
Working with JSON Data#
create_json_entry() stores data as a JSON attachment and adds a text entry with a formatted preview of it.
data = {
"experiment_id": "EXP-123",
"results": [1.2, 3.4, 5.6],
"status": "complete"
}
# Creates both an attachment entry and a text entry preview
file_entry, text_entry = page.entries.create_json_entry(data)
Modifying Entries#
Assigning to entry.content sends an update request to LabArchives. Unknown, unimplemented, and widget entries do not support updates and raise NotImplementedError.
entry = page.entries[0]
entry.content = "New content for the entry"
For attachments, assign a new Attachment to attachment_entry.content to replace the uploaded file.
new_attachment = Attachment.from_file("updated_data.csv")
attachment_entry.content = new_attachment