httk.serve.optimade

Submodules

Attributes

Exceptions

OptimadeClientError

Base class for safe, client-side OPTIMADE failures.

OptimadeDiscoveryError

An /info document was malformed or inconsistent for discovery.

OptimadeErrorDocumentError

A non-success response supplied a parseable OPTIMADE errors document.

OptimadeHTTPError

A remote endpoint returned a non-success HTTP status.

OptimadeTransportError

The HTTP client could not complete a request.

OptimadeVersionNegotiationError

An OPTIMADE base URL could not be negotiated to a supported API version.

OptimadeError

Common base class for all non-exit exceptions.

TranslatorError

Common base class for all non-exit exceptions.

CountUnavailableError

The service omitted a valid filtered meta.data_available count.

OptimadePaginationError

A remote continuation was unsafe, malformed, or non-terminating.

OptimadeResponseError

A successful HTTP response was not a usable OPTIMADE entry document.

Classes

BackendAdapter

Binds a store to the OPTIMADE entry endpoints it serves.

EntrySource

One queryable source (table/type) behind an OPTIMADE entry endpoint.

InMemoryStore

A store over dict rows: InMemoryStore({'structures': [ {...}, ... ]}).

OptimadeStore

A synchronous read-only OPTIMADE service connection with eager discovery.

RemoteEntryType

One immutable remote entry endpoint discovered from /info.

EndpointResponse

A response produced by an endpoint, to be serialized by the web layer.

OptimadeConfig

Configuration of a served OPTIMADE database.

RawRequest

An incoming OPTIMADE request, as handed over by the web layer.

ValidatedParameters

Validated URL query parameters of an OPTIMADE request.

ValidatedRequest

The result of validating a RawRequest.

RemoteResultColumn

One named scalar projection from a lazy remote result set.

RemoteResultSet

A frozen, lazy and re-iterable remote OPTIMADE result plan.

RemoteSearcher

One portable single-root OPTIMADE query under construction.

Functions

create_asgi_app(→ starlette.applications.Starlette)

Create an ASGI application serving an OPTIMADE API for the given backend.

serve(→ None)

Serve an OPTIMADE API for the given backend with a development web server.

adapter_from_providers(...)

Build a BackendAdapter serving the given entry providers.

providers_from_registry(→ dict[str, ...)

Return the registered entry-provider factories keyed by their registered name.

process(...)

Process an OPTIMADE query.

process_init(→ None)

Precompute the number of available entries per entry endpoint.

Package Contents

httk.serve.optimade.create_asgi_app(adapter: httk.serve.optimade.backend.adapter.BackendAdapter, config: httk.serve.optimade.model.config.OptimadeConfig | None = None, *, baseurl: str | None = None, debug: bool = False) starlette.applications.Starlette[source]

Create an ASGI application serving an OPTIMADE API for the given backend.

httk.serve.optimade.serve(adapter: httk.serve.optimade.backend.adapter.BackendAdapter, config: httk.serve.optimade.model.config.OptimadeConfig | None = None, *, host: str = '127.0.0.1', port: int = 8080, baseurl: str | None = None, debug: bool = False) None[source]

Serve an OPTIMADE API for the given backend with a development web server.

class httk.serve.optimade.BackendAdapter[source]

Binds a store to the OPTIMADE entry endpoints it serves.

sources maps entry endpoint names (e.g. 'structures') to the sources queried for that endpoint; an endpoint with several sources (e.g. several calculation result types) is queried across all of them.

schema is required: it declares the served entry types and properties. field_handlers maps each entry type to its filter-handler table. When omitted (left empty) it is derived from schema via simple_property_handlers(), using an identity property-key map (each property is filtered against a backend field of the same name); a backend whose field names differ, or that wants finer control, supplies its own tables instead.

store: httk.data.query.Store
sources: collections.abc.Mapping[str, collections.abc.Sequence[EntrySource]]
schema: httk.serve.optimade.schema.served.ServedSchema
field_handlers: collections.abc.Mapping[str, httk.data.optimade_query.HandlerTable]
query_function() httk.serve.optimade.model.results.QueryFunction[source]
class httk.serve.optimade.EntrySource[source]

One queryable source (table/type) behind an OPTIMADE entry endpoint.

target is what gets passed to searcher.variable(); fields maps OPTIMADE response-field names to extractors applied to matched row objects. relationships, when set, is an extractor mapping a matched row to a dictionary keyed by related entry type, each value a list of {'id': str, 'description': str?, 'role': str?} dictionaries. sort_keys maps response-field names to the backend field names to sort on. property_metadata maps response-field names to extractors returning the per-property metadata dictionary for a matched row (or None when there is no metadata for that row).

target: Any
fields: collections.abc.Mapping[str, FieldExtractor]
sort_keys: collections.abc.Mapping[str, str]
relationships: FieldExtractor | None = None
property_metadata: collections.abc.Mapping[str, FieldExtractor]
class httk.serve.optimade.InMemoryStore(tables: dict[str, list[Row]])[source]

A store over dict rows: InMemoryStore({'structures': [ {...}, ... ]}).

tables
searcher() MemorySearcher[source]
httk.serve.optimade.adapter_from_providers(providers: collections.abc.Iterable[httk.core.EntryProvider], **options: Any) httk.serve.optimade.backend.adapter.BackendAdapter[source]

Build a BackendAdapter serving the given entry providers.

Every provider’s entry_types() become served entry types (described by their EntryTypeDefinition), its property_keys() name the served subset and drive both the filter handlers (via simple_property_handlers()) and the response-field extractors, and its records() are loaded into an InMemoryStore. Every served property MUST be described by the entry type’s definition (a custom property must therefore live in an extended() definition); a ValueError names any offender. All served properties beyond id/type are marked default-response. Extra keyword options (e.g. sortable, recognized_prefixes) are forwarded to build_served_schema(); every served property is sortable-capable, since the provider’s property-key map is passed through as the source’s sort_keys.

Declared relationships (relationships()) are fully auto-wired for serving and filtering: for each entry type with declared relationships, a synthetic __rel_<related_type> id-list field is materialized on EVERY row of that entry type (an empty list when the row has no related entries of that type, so inverse set semantics are well-defined), and a '<related_type>.id' entry built with relationship_id_handler() is merged into the entry type’s derived filter-handler table (never overwriting an entry already present, mirroring how BackendAdapter respects explicitly supplied handler tables). <related_type>.id HAS ... filters — and, through the related-property resolver of translate_filter(), depth-1 relationship-property filters such as references.doi CONTAINS "10.1" — therefore work without any hand-wiring.

httk.serve.optimade.providers_from_registry() dict[str, collections.abc.Callable[Ellipsis, httk.core.EntryProvider]][source]

Return the registered entry-provider factories keyed by their registered name.

Resolves each factory registered via httk.core.register_entry_provider() (through httk.registry.* self-registration) into a callable. Providers need data, so applications instantiate them: providers_from_registry()["atomistic-structures"](data).

httk.serve.optimade.ALL_ADVERTISED[source]
exception httk.serve.optimade.OptimadeClientError[source]

Bases: RuntimeError

Base class for safe, client-side OPTIMADE failures.

exception httk.serve.optimade.OptimadeDiscoveryError(source_url: str, detail: str)[source]

Bases: OptimadeClientError

An /info document was malformed or inconsistent for discovery.

source_url
detail
exception httk.serve.optimade.OptimadeErrorDocumentError(source_url: str, status_code: int, detail: str | None = None)[source]

Bases: OptimadeHTTPError

A non-success response supplied a parseable OPTIMADE errors document.

exception httk.serve.optimade.OptimadeHTTPError(source_url: str, status_code: int, detail: str | None = None)[source]

Bases: OptimadeClientError

A remote endpoint returned a non-success HTTP status.

source_url
status_code
detail = None
class httk.serve.optimade.OptimadeStore(base_url: str, *, client: object | None = None, page_limit: int = 100, max_pages: int = 10000, allow_cross_origin_pagination: bool = False, response_fields: object | None = None)[source]

A synchronous read-only OPTIMADE service connection with eager discovery.

requested_base_url
base_url
page_limit = 100
max_pages = 10000
allow_cross_origin_pagination = False
response_fields = None
api_version: str | None = None
property entry_types: tuple[RemoteEntryType, Ellipsis]

Discovered entry endpoints in the service-advertised order.

property entry_types_by_name: collections.abc.Mapping[str, RemoteEntryType]

An immutable transport-name lookup for entry_types.

entry_type(name: str) RemoteEntryType[source]

Return one discovered endpoint by its transport name.

refresh() None[source]

Atomically replace discovery state after a fully successful rediscovery.

close() None[source]

Close an internally owned HTTP client; borrowed clients stay open.

searcher(*, response_fields: object = ...) httk.serve.optimade.remote_query.RemoteSearcher[source]

Create one synchronous, read-only remote search plan.

Passing response_fields overrides the store-level selection. An omitted value inherits it, while explicit None requests the service default.

exception httk.serve.optimade.OptimadeTransportError(source_url: str, detail: str)[source]

Bases: OptimadeClientError

The HTTP client could not complete a request.

source_url
detail
exception httk.serve.optimade.OptimadeVersionNegotiationError(source_url: str, detail: str)[source]

Bases: OptimadeClientError

An OPTIMADE base URL could not be negotiated to a supported API version.

source_url
detail
class httk.serve.optimade.RemoteEntryType[source]

One immutable remote entry endpoint discovered from /info.

name is solely the service’s transport endpoint name. Semantic recognition is intentionally represented by binding and is derived exclusively from definition IRIs.

name: str
definition_id: str | None
schema: httk.core.OptimadeSchemaSnapshot
property_iris: collections.abc.Mapping[str, str]
property_names: collections.abc.Mapping[str, str]
property_types: collections.abc.Mapping[str, tuple[str, str | None]]
advertised_properties: tuple[str, Ellipsis]
default_response_properties: tuple[str, Ellipsis]
sortable_properties: tuple[str, Ellipsis]
binding: httk.core.OptimadeEntryBinding | None
backend: type
httk.serve.optimade.process(request: httk.serve.optimade.model.request.RawRequest, query_function: httk.serve.optimade.model.results.QueryFunction, version: str, config: httk.serve.optimade.model.config.OptimadeConfig, schema: httk.serve.optimade.schema.served.ServedSchema, *, debug: bool = False) httk.serve.optimade.model.request.EndpointResponse[source]

Process an OPTIMADE query.

request carries the incoming request; only baseurl and representation must be set, missing information is derived from representation. query_function is the callback used to execute entry queries against the backend. schema describes the served entry types and properties.

httk.serve.optimade.process_init(config: httk.serve.optimade.model.config.OptimadeConfig, query_function: httk.serve.optimade.model.results.QueryFunction, schema: httk.serve.optimade.schema.served.ServedSchema, *, debug: bool = False) None[source]

Precompute the number of available entries per entry endpoint.

class httk.serve.optimade.EndpointResponse[source]

A response produced by an endpoint, to be serialized by the web layer.

Either json_response (a JSON:API document) or content (a raw body) is set.

response_code: int = 200
response_msg: str = 'OK'
content_type: str = 'application/vnd.api+json'
encoding: str = 'utf-8'
content: str | None = None
json_response: dict[str, Any] | None = None
class httk.serve.optimade.OptimadeConfig[source]

Configuration of a served OPTIMADE database.

implementation extends/overrides the fields of the meta -> implementation dictionary (e.g. issue_tracker, source_url, maintainer). database, schema_url, and request_delay populate the corresponding optional meta fields (OPTIMADE v1.2+) when set. license, available_licenses, and available_licenses_for_entries populate the corresponding optional base-info attributes when set. data_available is filled in by process_init with the number of available entries per entry endpoint.

provider: dict[str, Any]
implementation: dict[str, Any]
database: dict[str, Any] | None = None
schema_url: str | None = None
request_delay: float | None = None
license: dict[str, Any] | str | None = None
available_licenses: list[str] | None = None
available_licenses_for_entries: list[str] | None = None
data_available: dict[str, int]
partial_data_chunk_size: int = 1000
cors_origins: tuple[str, Ellipsis] = ()
exception httk.serve.optimade.OptimadeError(message: str, response_code: int, response_message: str, longmsg: str | None = None)[source]

Bases: Exception

Common base class for all non-exit exceptions.

response_code
response_msg
content
class httk.serve.optimade.RawRequest[source]

An incoming OPTIMADE request, as handed over by the web layer.

Only baseurl and representation are mandatory; missing information is derived from representation during validation.

baseurl: str
representation: str
relurl: str | None = None
querystr: str | None = None
query: dict[str, str] | None = None
endpoint: str | None = None
request_id: str | None = None
version: str | None = None
exception httk.serve.optimade.TranslatorError(message: str, response_code: int, response_message: str, longmsg: str | None = None)[source]

Bases: OptimadeError

Common base class for all non-exit exceptions.

class httk.serve.optimade.ValidatedParameters[source]

Validated URL query parameters of an OPTIMADE request.

response_format: str = 'json'
page_limit: int = 50
page_offset: int = 0
response_fields: str | None = None
filter: str | None = None
sort: str | None = None
include: str | None = None
dimension_slices: dict[str, RequestedSlice]
as_query_dict() dict[str, str][source]

Return the parameters as a URL query dict, omitting unset values.

class httk.serve.optimade.ValidatedRequest[source]

The result of validating a RawRequest.

baseurl: str
representation: str
endpoint: str
version: str
query: ValidatedParameters
url_version: str | None = None
request_id: str | None = None
recognized_response_fields: list[str] = []
unrecognized_response_fields: list[str] = []
sort_fields: list[tuple[str, bool]] = []
include_paths: list[str] = []
property_metadata_requested: bool = False
partial_data_parts: tuple[str, str, str] | None = None
partial_data_offset: int = 0
warnings: list[dict[str, Any]] = []
exception httk.serve.optimade.CountUnavailableError[source]

Bases: OptimadeResponseError, httk.data.CountUnavailableError

The service omitted a valid filtered meta.data_available count.

exception httk.serve.optimade.OptimadePaginationError[source]

Bases: OptimadeResponseError

A remote continuation was unsafe, malformed, or non-terminating.

exception httk.serve.optimade.OptimadeResponseError[source]

Bases: httk.serve.optimade.client.OptimadeClientError

A successful HTTP response was not a usable OPTIMADE entry document.

class httk.serve.optimade.RemoteResultColumn(result: RemoteResultSet, index: int)[source]

One named scalar projection from a lazy remote result set.

name
class httk.serve.optimade.RemoteResultSet(searcher: RemoteSearcher, outputs: collections.abc.Mapping[str, object] | None = None)[source]

A frozen, lazy and re-iterable remote OPTIMADE result plan.

names
first() httk.data.ResultRow | None[source]
one() httk.data.ResultRow[source]
scalars(name: str | None = None) collections.abc.Iterator[object][source]
column(name: str) RemoteResultColumn[source]
abstractmethod cursor() collections.abc.Iterator[httk.data.ResultRow][source]
class httk.serve.optimade.RemoteSearcher(store: httk.serve.optimade.client.OptimadeStore, *, response_fields: object = None)[source]

One portable single-root OPTIMADE query under construction.

offset = 0
variable(target: object) _RemoteVariable[source]
add(expression: object) None[source]
output(variable: object, name: str) None[source]
add_sort(field: object, descending: bool = False) None[source]
set_limit(limit: int) None[source]
add_offset(offset: int) None[source]
count() int[source]
results(**outputs: object) RemoteResultSet[source]