benchling_sdk.apps.helpers.session_helpers module¶

exception AppUserFacingError¶

Bases: Exception

App User Facing Error.

Extend this class with custom exceptions you want to be written back to the user as a SessionMessage.

SessionClosingContextExitHandler will invoke messages() and write them to a user. Callers choosing to write their own SessionContextExitHandler may need to replicate this behavior themselves.

This is useful for control flow where an app wants to terminate with an error state that is resolvable by the user.

For example:

class InvalidUserInputError(AppUserFacingError):

pass

raise InvalidUserInputError(“Please enter a number between 1 and 10”)

This would create a message shown to the user like:

AppSessionMessageCreate(“Please enter a number between 1 and 10”, style=AppSessionMessageStyle.ERROR)

__init__(messages: Union[str, List[str]], *args) → None¶

Initialize an AppUserFacingError with one message or a list.

messages() → List[AppSessionMessageCreate]¶

Create a series of AppSessionMessageCreate to write to a Session and displayed to the user.

class AppUserFacingErrorProcessor¶

Bases: benchling_sdk.apps.helpers.session_helpers.SessionContextErrorProcessor

App User Facing Error Processor.

An error processor for surfacing error messages directly back to a user.

Most uncaught exceptions should not be exposed to users to avoid leaking information. App developers may curate specific exception types that extend AppUserFacingError. They may stop control flow and also write the message directly back to the user.

classmethod handles(exc_type: Type[BaseException], exc_value: BaseException, exc_traceback: TracebackType) → bool¶

Register AppUserFacingError as the types to process.

classmethod process_error(context: SessionContextManager[benchling_sdk.apps.framework.AppType], exc_type: Type[BaseException], exc_value: BaseException, exc_traceback: TracebackType) → bool¶

Process AppUserFacingError.

Writes a message back to the user with the error’s messages and closes the session as FAILED.

If an exception is supplied, and the method wishes to suppress the exception (i.e., prevent it from being propagated), it should return a True value. Otherwise, the exception will be processed normally upon exit from this method.

class BenchlingBadRequestErrorProcessor¶

Bases: benchling_sdk.apps.helpers.session_helpers.AppUserFacingErrorProcessor

Benchling Bad Request Error Processor.

Attempts to surface 400 Bad Request errors from the API back to the user as AppUserFacingErrors. These errors may be a result of user inputs they have the opportunity to correct.

classmethod handles(exc_type: Type[BaseException], exc_value: BaseException, exc_traceback: TracebackType) → bool¶

Register BenchlingError with status_code 400 as the types to process.

classmethod process_error(context: SessionContextManager[benchling_sdk.apps.framework.AppType], exc_type: Type[BaseException], exc_value: BaseException, exc_traceback: TracebackType) → bool¶

Process BenchlingError for API bad requests.

Writes a message back to the user with the error’s messages and closes the session as FAILED.

exception InvalidSessionTimeoutError¶

Bases: Exception

Invalid Session Timeout Error.

A session’s timeout value was set to an invalid value.

exception MissingAttachedCanvasError¶

Bases: Exception

Missing Attached Canvas Error.

A canvas operation was requested, but a session context has no attached canvas.

exception SessionClosedError¶

Bases: Exception

Session Closed Error.

A session was inoperable because its status in Benchling was terminal.

class SessionClosingContextExitHandler¶

Bases: benchling_sdk.apps.helpers.session_helpers.SessionContextExitHandler

Session Closing Context Exit Handler.

Defines behavior when exiting a session context. This implementation only calls the handler

On success: close the Session with Benchling with SessionStatusUpdate.SUCCEEDED. If success_messages were specified, those will also be written to the Session when setting the status.

On error: close the Session with Benchling with SessionStatusUpdate.FAILED. If error_messages were specified, those will also be written to the Session when setting the status.

As a best practice, error messages are not written to the session to avoid leaking potentially sensitive information.

__init__(success_messages: Optional[Iterable[AppSessionMessageCreate]] = None, error_messages: Optional[Iterable[AppSessionMessageCreate]] = [AppSessionMessageCreate(_DEFAULT_APP_ERROR_MESSAGE, style=AppSessionMessageStyle.ERROR)], error_processors: List[Type[SessionContextErrorProcessor]] = [AppUserFacingErrorProcessor, BenchlingBadRequestErrorProcessor])¶

Init Session Closing Context Exit Handler.

Specify an ordered list of SessionContextErrorProcessor types to error_processors for custom handling of specific exception types. Processors earlier in the list are matched first.

on_error(context: SessionContextManager[benchling_sdk.apps.framework.AppType], exc_type: Type[BaseException], exc_value: BaseException, exc_traceback: TracebackType) → bool¶

Close Active Session on Error.

A SessionErrorExitHandler which will close an active session when the wrapping session context exits with any type of Exception.

Sets the status as AppSessionUpdateStatus.FAILED and will set the message to the specified text, if provided, with a AppSessionMessageStyle.ERROR.

If an exception is supplied, and the method wishes to suppress the exception (i.e., prevent it from being propagated), it should return a True value. Otherwise, the exception will be processed normally upon exit from this method.

on_success(context: SessionContextManager[benchling_sdk.apps.framework.AppType]) → bool¶

Close Active Session on Success.

A SessionSuccessExitHandler which will close an active session when the wrapping session context exits.

Sets the status as AppSessionUpdateStatus.SUCCEEDED and will set the message to the specified text, if provided, with an AppSessionMessageStyle.SUCCESS.

Generally prefer apps to manually close_session() with more informative success messages, but this provides a fallback in case the context exits without error first.

exception SessionContextClosedError¶

Bases: Exception

Session Context Closed Error.

An operation was attempted using the session context manager after it was closed.

class SessionContextEnterHandler¶

Bases: abc.ABC, Generic[benchling_sdk.apps.framework.AppType]

Session Context Enter Handler.

An abstract class for defining behavior when a session context’s __enter__ method is called.

abstract on_enter(context: SessionContextManager[benchling_sdk.apps.framework.AppType]) → None¶

Perform on session context enter after a Session has been started with Benchling.

class SessionContextErrorProcessor¶

Bases: abc.ABC

Session Context Error Processor.

Implement to match a one or more exception matchers specified by handles to be processed by process_error in the event of a session context exit with errors.

process_error() does not assume a context’s session is active. If using the session with process_error(), this should be checked.

For user with SessionClosingContextExitHandler or its subclasses.

abstract classmethod handles(exc_type: Type[BaseException], exc_value: BaseException, exc_traceback: TracebackType) → bool¶

Return True if the exception should be delegated to this handler.

abstract classmethod process_error(context: SessionContextManager[benchling_sdk.apps.framework.AppType], exc_type: Type[BaseException], exc_value: BaseException, exc_traceback: TracebackType) → bool¶

Process error.

Receives one of the exceptions matched by handles() and takes further action. Returns bool to the __exit__ of the context manager.

If an exception is supplied, and the method wishes to suppress the exception (i.e., prevent it from being propagated), it should return a True value. Otherwise, the exception will be processed normally upon exit from this method.

class SessionContextExitHandler¶

Bases: abc.ABC, Generic[benchling_sdk.apps.framework.AppType]

Session Context Exit Handler.

An abstract class for defining behavior when a session context’s __exit__ method is called.

abstract on_error(context: SessionContextManager[benchling_sdk.apps.framework.AppType], exc_type: Type[BaseException], exc_value: BaseException, exc_traceback: TracebackType) → bool¶

Perform when an error caused the session context to exit.

Returns a bool to indicate context __exit__ behavior.

If an exception is supplied, and the method wishes to suppress the exception (i.e., prevent it from being propagated), it should return a True value. Otherwise, the exception will be processed normally upon exit from this method.

abstract on_success(context: SessionContextManager[benchling_sdk.apps.framework.AppType]) → bool¶

Perform on session context exit when no errors are present.

Returns a bool to indicate context __exit__ behavior.

If an exception is supplied, and the method wishes to suppress the exception (i.e., prevent it from being propagated), it should return a True value. Otherwise, the exception will be processed normally upon exit from this method.

class SessionContextManager¶

Bases: contextlib.AbstractContextManager, Generic[benchling_sdk.apps.framework.AppType]

Manage Benchling App Session.

On init, will invoke SessionProvider to get a session accordingly. When exiting the session context, will invoke error_exit_handler if an exception is encountered. Otherwise, invokes the success_exit_handler.

__init__(app: benchling_sdk.apps.framework.AppType, session_provider: SessionProvider, context_enter_handler: Optional[SessionContextEnterHandler[benchling_sdk.apps.framework.AppType]] = None, context_exit_handler: Optional[SessionContextExitHandler[benchling_sdk.apps.framework.AppType]] = None)¶

Initialize SessionContextManager.

Prefer new_session_context() or continue_session_context() over initializing this directly unless it’s necessary to extend this class.

active_session() → Optional[AppSession]¶

Active Session.

Return an active Session held by the session context. Return None if the context does not have an active Session.

add_timeout_seconds(seconds_to_add: int) → None¶

Add Session Timeout Seconds.

Add seconds to the session’s timeout in Benchling. Requires an active session which is unclosed.

property app: benchling_sdk.apps.framework.AppType¶

Return the app for the session.

attach_canvas(canvas_id: str) → None¶

Attach Canvas.

Updates the specified canvas_id with the active session_id, causing session information to display on the specified canvas.

close_session(status: AppSessionUpdateStatus, messages: Optional[Iterable[AppSessionMessageCreate]] = None)¶

Close Session.

Closes the session with Benchling on the server. This MUST be the last call in the session context.

This will close the session. Subsequent attempts to perform session operations may raise SessionContextClosedError.

Do not continue performing operations in the session context after calling close_session().

detach_canvas() → None¶

Detach Canvas.

Updates the attached canvas in the context to remove the session_id. This will cause the canvas to cease displaying session information and messages.

Requires that attach_canvas() was called previously, or an error will be raised.

has_active_session() → bool¶

Has Active Session.

Return True if the active Session with Benchling has not been closed by the session context.

set_timeout_seconds(timeout_seconds: int) → None¶

Set Session Timeout.

Sets the session’s timeout in Benchling. Requires an active session which is unclosed.

Timeouts may only be increased, up to the Benchling allowed maximum.

write_messages(messages: Iterable[AppSessionMessageCreate]) → None¶

Write Session Messages.

Write one or more messages to app’s session. Requires an active session which is unclosed.

write_strings(contents: Union[str, Iterable[str]], style: Union[AppSessionMessageStyle, benchling_api_client.v2.types.Unset] = UNSET) → None¶

Write Session Messages from string contents.

Shorthand for writing session messages without creating an AppSessionMessageCreate instance.

Write one or more messages to app’s session from the specified contents string(s). If passed an iterable, each element will create its own session message. If style is specified, it will be applied to all messages.

For more granular control, use write_messages().

Requires an active session which is unclosed.

class SessionProvider¶

Bases: Protocol

Provide a Benchling App Session to convey app status.

__init__(*args, **kwargs)¶
continue_session_context(app: benchling_sdk.apps.framework.AppType, session_id: str, context_enter_handler: Optional[SessionContextEnterHandler] = None, context_exit_handler: Optional[SessionContextExitHandler] = None) → SessionContextManager[benchling_sdk.apps.framework.AppType]¶

Continue Session Context.

Create a context manager that will fetch an existing Session from Benchling and create a context with it.

create_session_provider(app: benchling_sdk.apps.framework.AppType, name: str, timeout_seconds: int) → SessionProvider¶

Create Session Provider.

Create a SessionProvider that will create a new session with the specified app. This is the preferred way of working with sessions for most apps.

existing_session_provider(app: benchling_sdk.apps.framework.AppType, session_id: str) → SessionProvider¶

Existing Session Provider.

Create a SessionProvider that will fetch the existing session by ID using the app’s Benchling instance. This might be used in cases like distributed apps which may be sharing a session and passing a reference to the handle (session ID).

new_session_context(app: benchling_sdk.apps.framework.AppType, name: str, timeout_seconds: int, context_enter_handler: Optional[SessionContextEnterHandler] = None, context_exit_handler: Optional[SessionContextExitHandler] = None) → SessionContextManager[benchling_sdk.apps.framework.AppType]¶

Create New Session Context.

Create a context manager that will provision a new app Session with Benchling.

ref(reference: Union[AaSequence, Blob, Box, Container, CustomEntity, DnaSequence, DnaOligo, Entry, Folder, Location, Mixture, Plate, RnaOligo, Molecule, RnaSequence, Request, WorkflowOutput, WorkflowTask]) → str¶

Ref.

Helper method for easily serializing a referenced object into a string embeddable in AppSessionMessageCreate content.

Example:

dna_sequence = benchling.dna_sequences.get_by_id(“seq_1234”) AppSessionMessageCreate(f”This is my DNA sequence {ref(dna_sequence)} for analysis”