httk.serve.optimade

Public generic OPTIMADE serving, client, and query APIs.

Submodules

Attributes

Exceptions

OptimadeClientError

Base class for safe, client-side OPTIMADE failures.

OptimadeDiscoveryError

Report a malformed or inconsistent /info discovery document.

OptimadeErrorDocumentError

Report a non-success response with a parseable OPTIMADE error document.

OptimadeHTTPError

Report a non-success HTTP status from a remote endpoint.

OptimadeTransportError

Report that the HTTP client could not complete a request.

OptimadeVersionNegotiationError

Report failure to negotiate a supported OPTIMADE API version.

OptimadeError

Represent an OPTIMADE response error.

TranslatorError

Represent a filter translation failure with an HTTP response contract.

CountUnavailableError

The service omitted a valid filtered meta.data_returned 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

Bind a store to the OPTIMADE entry endpoints it serves.

EntrySource

Describe one queryable source behind an OPTIMADE entry endpoint.

InMemoryStore

Provide a store over dictionary rows.

StoredBackendAdapter

Serve one data federation per OPTIMADE entry type.

OptimadeStore

Connect synchronously to a read-only OPTIMADE service and discover it eagerly.

RemoteEntryType

Describe one immutable remote entry endpoint discovered from /info.

EndpointResponse

Represent an endpoint response for serialization by the web layer.

OptimadeConfig

Configure a served OPTIMADE database.

OptimadeIndexConfig

Configure an OPTIMADE index meta-database.

RawRequest

Represent an incoming OPTIMADE request from the web layer.

ValidatedParameters

Represent validated URL query parameters of an OPTIMADE request.

ValidatedRequest

Represent the result of validating a RawRequest.

RemoteResultColumn

Expose one named scalar projection from a lazy result set.

RemoteResultSet

Represent a frozen, lazy, and re-iterable remote result plan.

RemoteSearcher

Build one portable single-root OPTIMADE query.

Functions

create_asgi_app(adapter[, config, baseurl, debug, ...])

Create an ASGI application serving an OPTIMADE API for a backend or store.

create_index_asgi_app(config, *[, baseurl, debug, ...])

Create an ASGI application for an OPTIMADE index meta-database.

serve(adapter[, config, host, port, baseurl, debug, ...])

Serve an OPTIMADE API for a backend or entry store with a development server.

adapter_from_providers(providers, **options)

Build a BackendAdapter serving the given entry providers.

adapter_from_store(store, **options)

Build a lazy OPTIMADE adapter from every described family in one store.

adapter_from_stores(sources, **options)

Build a lazy store-backed adapter from durable entry sources.

providers_from_registry()

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

process(request, query_function, version, config, ...)

Process one OPTIMADE query.

Package Contents

httk.serve.optimade.create_asgi_app(adapter, config=None, *, baseurl=None, debug=False, report_level='warning', report_context_levels=None)[source]

Create an ASGI application serving an OPTIMADE API for a backend or store.

An absent baseurl makes the application derive a mount-aware URL from the request. An explicit value is authoritative.

Parameters:
Returns:

Configured serving application.

Return type:

httk.serve.http.ServeApp

httk.serve.optimade.create_index_asgi_app(config, *, baseurl=None, debug=False, report_level='warning', report_context_levels=None)[source]

Create an ASGI application for an OPTIMADE index meta-database.

The index serves only discovery, links, and unversioned version negotiation. It has no backend adapter and performs no query calls. The supplied configuration is retained as the response metadata source; the composed application’s caller owns its lifetime and configuration.

Parameters:
Returns:

Configured serving application.

Raises:

TypeError – If config is not an OptimadeIndexConfig.

Return type:

httk.serve.http.ServeApp

httk.serve.optimade.serve(adapter, config=None, *, host='127.0.0.1', port=8080, baseurl=None, debug=False, report_level='warning', report_context_levels=None)[source]

Serve an OPTIMADE API for a backend or entry store with a development server.

Parameters:
class httk.serve.optimade.BackendAdapter[source]

Bind 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.

Parameters:
  • store – Store implementing the neutral query protocol.

  • sources – Queryable sources keyed by entry endpoint.

  • schema – Required schema describing served entries and properties.

  • field_handlers – Optional filter handlers keyed by entry endpoint.

store: httk.store.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.store.query.optimade_filters.HandlerTable]
query_function()[source]

Return the callback that executes queries through this adapter.

Returns:

Query callback consumed by the OPTIMADE request engine.

Return type:

httk.serve.optimade.model.results.QueryFunction

class httk.serve.optimade.EntrySource[source]

Describe one queryable source 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).

Parameters:
  • target – Store-specific target passed to searcher.variable.

  • fields – Response-field extractors applied to matched rows.

  • sort_keys – Response-field to backend-sort-field mappings.

  • relationships – Optional extractor for related-resource data.

  • property_metadata – Optional per-property metadata extractors.

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)[source]

Provide a store over dictionary rows.

Parameters:

tables (dict[str, list[Row]]) – Row lists keyed by table name.

tables
searcher(*, as_of=None)[source]

Create a searcher over this store’s tables.

Parameters:

as_of (object) – Optional historic timestamp cutoff; unsupported here.

Returns:

Fresh in-memory searcher.

Raises:

ValueError – If a historic cutoff is requested.

Return type:

MemorySearcher

class httk.serve.optimade.StoredBackendAdapter[source]

Serve one data federation per OPTIMADE entry type.

Parameters:
  • federations – Durable federations keyed by entry endpoint.

  • schema – Schema describing the federations’ served entries.

federations: collections.abc.Mapping[str, Any]
schema: httk.serve.optimade.schema.served.ServedSchema
snapshot_cutoff_ns(entry_type, now_ns)[source]

Return the resolution-aware snapshot cutoff for one entry type.

query_function()[source]

Return the callback that queries the configured federations.

Returns:

Query callback consumed by the OPTIMADE request engine.

Return type:

httk.serve.optimade.model.results.QueryFunction

httk.serve.optimade.adapter_from_providers(providers, **options)[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.

Parameters:
Returns:

Fully wired in-memory backend adapter.

Raises:

ValueError – If provider keys or served properties are invalid.

Return type:

httk.serve.optimade.backend.adapter.BackendAdapter

httk.serve.optimade.adapter_from_store(store, **options)[source]

Build a lazy OPTIMADE adapter from every described family in one store.

Families declared without an entry-type definition are deliberately ignored. This lets application-specific records, such as DSP publication declarations, coexist with OPTIMADE records in one durable layout.

Parameters:
  • store (httk.store.EntryStore) – Entry store whose configured layout is discovered.

  • **options (Any) – Schema options forwarded to adapter_from_stores().

Returns:

Lazy adapter over all configured OPTIMADE families.

Raises:
  • TypeError – If store does not implement EntryStore.

  • ValueError – If the store contains no OPTIMADE-described family.

Return type:

StoredBackendAdapter

httk.serve.optimade.adapter_from_stores(sources, **options)[source]

Build a lazy store-backed adapter from durable entry sources.

Sources with the same exact logical family are federated under one entry endpoint. The data layer owns all source/backing traversal and global pagination; this adapter advertises the family’s definition and turns only the returned page into OPTIMADE result rows.

Parameters:
Returns:

Lazy adapter over the supplied durable sources.

Raises:
  • ValueError – If sources conflict or expose incomplete sort mappings.

  • TypeError – If a source is not a stored entry source.

Return type:

StoredBackendAdapter

httk.serve.optimade.providers_from_registry()[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).

Returns:

Registered provider factories keyed by registry name.

Return type:

dict[str, collections.abc.Callable[Ellipsis, httk.core.EntryProvider]]

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, detail)[source]

Bases: OptimadeClientError

Report a malformed or inconsistent /info discovery document.

Parameters:
  • source_url (str) – Redacted URL of the malformed document.

  • detail (str) – Safe discovery detail.

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

Bases: OptimadeHTTPError

Report a non-success response with a parseable OPTIMADE error document.

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

Bases: OptimadeClientError

Report a non-success HTTP status from a remote endpoint.

Parameters:
  • source_url (str) – Redacted URL of the response.

  • status_code (int) – HTTP status code returned by the service.

  • detail (str | None) – Optional safe error detail.

source_url
status_code
detail = None
class httk.serve.optimade.OptimadeStore(base_url, *, client=None, page_limit=50, max_pages=10000, allow_cross_origin_pagination=False, response_fields=None)[source]

Connect synchronously to a read-only OPTIMADE service and discover it eagerly.

Unversioned bases negotiate strictly through the preference-ordered /versions CSV. Query pagination validates complete pages before yielding, uses lazy one-root exact-literal requests, and bounds continuation links by page count and origin.

Parameters:
  • base_url (str) – Absolute HTTP(S) service base URL.

  • client (object | None) – Optional borrowed synchronous HTTP client.

  • page_limit (int) – Default remote page size.

  • max_pages (int) – Maximum continuation pages followed by one query.

  • allow_cross_origin_pagination (bool) – Permit continuation links on another origin.

  • response_fields (object | None) – Default response-field selection for new searchers.

Raises:
requested_base_url
base_url
page_limit = 50
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)[source]

Return one discovered endpoint by transport name.

Parameters:

name (str) – Service-advertised endpoint name.

Returns:

Discovered endpoint descriptor.

Raises:

KeyError – If no endpoint has that name.

Return type:

RemoteEntryType

refresh()[source]

Refresh discovery state after a fully successful rediscovery.

Raises:

OptimadeClientError – If the store is closed or discovery fails.

close()[source]

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

searcher(*, response_fields=..., as_of=None)[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.

Parameters:
  • response_fields (object) – Per-search field selection override.

  • as_of (object) – Historic cutoff; unsupported because remote snapshot negotiation is unavailable.

Returns:

New remote search plan.

Raises:
Return type:

httk.serve.optimade.remote_query.RemoteSearcher

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

Bases: OptimadeClientError

Report that the HTTP client could not complete a request.

Parameters:
  • source_url (str) – Redacted URL of the failed request.

  • detail (str) – Safe transport detail.

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

Bases: OptimadeClientError

Report failure to negotiate a supported OPTIMADE API version.

Parameters:
  • source_url (str) – Redacted URL used for negotiation.

  • detail (str) – Safe negotiation detail.

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

Describe 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.

Parameters:
  • name – Transport endpoint name.

  • definition_id – Entry-definition IRI, when advertised.

  • schema – Lossless schema snapshot from discovery.

  • property_iris – Transport property names keyed by definition IRI.

  • property_names – Local property names keyed by definition IRI.

  • property_types – Property kinds keyed by transport name.

  • advertised_properties – Properties advertised by the service.

  • default_response_properties – Properties returned by default.

  • sortable_properties – Properties accepted by remote sorting.

  • binding – Recognized semantic binding, when available.

  • backend – Backend class associated with the binding.

name: str
definition_id: str | None
schema: httk.core.optimade.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.register.OptimadeEntryBinding | None
backend: type
httk.serve.optimade.process(request, query_function, version, config, schema, *, snapshot_cutoff_ns=None, debug=False)[source]

Process one 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.

Parameters:
Returns:

Endpoint response before web serialization.

Raises:

httk.serve.optimade.model.errors.OptimadeError – If request validation or endpoint processing fails.

Return type:

httk.serve.optimade.model.request.EndpointResponse

class httk.serve.optimade.EndpointResponse[source]

Represent an endpoint response for serialization by the web layer.

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

Parameters:
  • response_code – HTTP status code.

  • response_msg – HTTP status title.

  • content_type – Response media type.

  • encoding – Response character encoding.

  • content – Raw response body, when the response is not JSON.

  • json_response – JSON:API response document, when the response is JSON.

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]

Configure 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.

Parameters:
  • provider – Provider metadata for the OPTIMADE response envelope.

  • links – Provider links exposed by the /links endpoint.

  • implementation – Implementation metadata merged into response metadata.

  • database – Optional database metadata for response metadata.

  • schema_url – URL of the served schema, when one is available.

  • request_delay – Optional advertised request delay.

  • license – License metadata exposed by the base-info endpoint.

  • available_licenses – Licenses advertised for the service.

  • available_licenses_for_entries – Licenses advertised for entries.

  • page_limit_max – Largest page_limit accepted; larger requests get a 403.

  • partial_data_chunk_size – Number of outer items emitted per partial-data page.

  • cors_origins – Exact browser origins allowed to make cross-origin requests.

Raises:

ValueError – If page_limit_max is not an integer >= 1.

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
page_limit_max: int = 50
partial_data_chunk_size: int = 1000
cors_origins: tuple[str, Ellipsis] = ()
exception httk.serve.optimade.OptimadeError(message, response_code, response_message, longmsg=None)[source]

Bases: Exception

Represent an OPTIMADE response error.

Parameters:
  • message (str) – Short error detail used as the exception message.

  • response_code (int) – HTTP status code returned to the client.

  • response_message (str) – HTTP status title returned to the client.

  • longmsg (str | None) – Optional longer error detail returned in the response.

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

Bases: OptimadeConfig

Configure an OPTIMADE index meta-database.

The links are the configured databases advertised by the index. Exactly one must have link_type == "root"; child links are the databases that may be selected as the index’s default relationship. The regular OptimadeConfig remains a non-index service configuration.

Parameters:

default_link_id – Identifier of the default configured child link, or None when the index has no default.

Raises:

ValueError – If configured links do not satisfy the links schema or the root/default-link constraints.

class httk.serve.optimade.RawRequest[source]

Represent an incoming OPTIMADE request from the web layer.

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

Parameters:
  • baseurl – Base URL used when generating response links.

  • representation – Request path and query representation.

  • relurl – Relative request URL, when supplied by the web layer.

  • querystr – Raw query string.

  • query – Parsed query parameters.

  • endpoint – Preselected endpoint, when supplied by the caller.

  • request_id – Preselected entry identifier, when supplied by the caller.

  • version – API version declared by the caller.

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, response_code, response_message, longmsg=None)[source]

Bases: OptimadeError

Represent a filter translation failure with an HTTP response contract.

class httk.serve.optimade.ValidatedParameters[source]

Represent validated URL query parameters of an OPTIMADE request.

Parameters:
  • response_format – Requested response format.

  • page_limit – Maximum number of entries in a page.

  • page_offset – Number of matching entries to skip.

  • response_fields – Comma-separated requested response fields.

  • filter – Raw OPTIMADE filter expression.

  • sort – Raw OPTIMADE sort expression.

  • include – Raw related-entry inclusion request.

  • as_of – Nanosecond timestamp cutoff for timestamp-capable stored sources; timestamp-disabled sources may serve current state and generic providers ignore it.

  • dimension_slices – Requested slices keyed by dimension name.

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
as_of: int | None = None
dimension_slices: dict[str, RequestedSlice]
as_query_dict()[source]

Return the parameters as a URL query mapping.

Returns:

Query values with unset optional parameters omitted.

Return type:

dict[str, str]

class httk.serve.optimade.ValidatedRequest[source]

Represent the result of validating a RawRequest.

Parameters:
  • baseurl – Base URL used when generating response links.

  • representation – Original request representation.

  • endpoint – Validated endpoint name.

  • version – Validated OPTIMADE version.

  • query – Validated query parameters.

  • url_version – Version segment present in the request URL.

  • request_id – Validated entry identifier.

  • recognized_response_fields – Requested fields known to the schema.

  • unrecognized_response_fields – Requested fields not known to the schema.

  • sort_fields – Validated sort fields and directions.

  • include_paths – Validated related-entry paths.

  • property_metadata_requested – Whether property metadata was requested.

  • partial_data_parts – Entry, identifier, and property for partial data.

  • partial_data_offset – Offset into a partial-data response.

  • warnings – Warnings collected while processing the request.

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.store.CountUnavailableError

The service omitted a valid filtered meta.data_returned 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, index)[source]

Expose one named scalar projection from a lazy result set.

Parameters:
  • result (RemoteResultSet) – Result set owning the projection.

  • index (int) – Zero-based projection index.

name
class httk.serve.optimade.RemoteResultSet(searcher, outputs=None)[source]

Represent a frozen, lazy, and re-iterable remote result plan.

Parameters:
names
first()[source]

Return the first result, if present.

Returns:

First row or None.

Return type:

httk.store.ResultRow | None

one()[source]

Return the only result.

Returns:

Sole result row.

Raises:
Return type:

httk.store.ResultRow

scalars(name=None)[source]

Iterate one named scalar output from each result.

Parameters:

name (str | None) – Output name, or None when exactly one exists.

Returns:

Iterator over scalar values.

Raises:
  • KeyError – If the named output is unknown.

  • ValueError – If no name is given and multiple outputs exist.

Return type:

collections.abc.Iterator[object]

column(name)[source]

Return a lazy column for a scalar output.

Parameters:

name (str) – Scalar output name.

Returns:

Lazy result column.

Raises:
  • KeyError – If the output is unknown.

  • TypeError – If the output is a whole-record projection.

Return type:

RemoteResultColumn

abstractmethod cursor()[source]

Reject unsupported cursor access.

Returns:

Never; remote OPTIMADE cursors are unsupported.

Raises:

NotImplementedError – Remote OPTIMADE cursors are unavailable.

Return type:

collections.abc.Iterator[httk.store.ResultRow]

class httk.serve.optimade.RemoteSearcher(store, *, response_fields=None)[source]

Build one portable single-root OPTIMADE query.

Parameters:
offset = 0
variable(target)[source]

Bind the query to one discovered remote entry type.

Parameters:

target (object) – Discovered entry descriptor or registered backend class.

Returns:

Query variable exposing portable fields.

Raises:

httk.store.query.protocols.UnsupportedQueryError – If the target is not recognized or a root variable is already bound.

Return type:

_RemoteVariable

add(expression)[source]

Add a filter expression to the query.

Parameters:

expression (object) – Expression created by this searcher.

Raises:
output(variable, name)[source]

Declare a whole-record or scalar output.

Parameters:
  • variable (object) – Root variable or field to project.

  • name (str) – Output name.

Raises:
add_sort(field, descending=False)[source]

Append a sortable field to the remote query.

Parameters:
  • field (object) – Field exposed by this searcher’s variable.

  • descending (bool) – Sort in descending order when true.

Raises:

httk.store.UnsupportedQueryError – If the field is not portable or sortable.

set_limit(limit)[source]

Set the query result limit.

Parameters:

limit (int) – Nonnegative limit, or a negative value for no bound.

add_offset(offset)[source]

Advance the query offset.

Parameters:

offset (int) – Nonnegative number of matching rows to skip.

count()[source]

Return the filtered remote count.

Returns:

meta.data_returned reported by the service.

Raises:

CountUnavailableError – If the service omits a valid count.

Return type:

int

results(**outputs)[source]

Freeze the query as a lazy, re-iterable result set.

Parameters:

**outputs (object) – Optional output names mapped to this searcher’s projections.

Returns:

Frozen remote result plan.

Raises:

ValueError – If no outputs are declared.

Return type:

RemoteResultSet