API reference¶
Some parts of the API are described on separate pages:
sdmx.writer: Write standard formats.sdmx.sourceon the page Data sources.
See also the Implementation notes.
On this page:
Top-level methods and classes¶
|
Client for a SDMX REST web service. |
|
Enumeration of SDMX-REST API resources. |
|
Add a new data source. |
|
Return the Source with the given id. |
|
Install SDMX-ML XML Schema documents for use with |
Return a sorted list of valid source IDs. |
|
Top-level logger. |
|
|
Read a |
|
Request a URL directly. |
|
Convert an SDMX obj to SDMX-CSV. |
|
Convert an SDMX obj to |
|
Convert an SDMX obj to SDMX-ML. |
|
Convert data in non-SDMX formats and data structures to SDMX |
|
Validate SDMX-ML in msg against the XML Schema (XSD) documents. |
- class sdmx.Client(source=None, *, session: Session | None = None, log_level=None, **session_opts)[source]¶
Client for a SDMX REST web service.
- Parameters:
source (
strorsource.Source) – Identifier of a data source. If a string, must be one of the known sources inlist_sources().session (
requests.sessions.Session) –requests.Sessioninstance. If not supplied, an instance ofSessionis created.log_level (
int) –Override the package-wide logger with one of the standard logging levels.
Deprecated since version 2.0: Will be removed in
sdmxversion 3.0.**session_opts – Additional keyword arguments are passed to
Sessionand thus torequests_cache.CachedSessionand its backend classes (if installed).
- get(resource_type: str | Resource | None = None, resource_id: str | None = None, tofile: os.PathLike | IO | None = None, use_cache: bool = False, dry_run: bool = False, **kwargs) sdmx.message.Message | requests.Request[source]¶
Retrieve SDMX data or metadata.
(Meta)data is retrieved from the
sourceof the current Client. The item(s) to retrieve can be specified in one of two ways:resource_type, resource_id: These give the type (see
Resource) and, optionally, ID of the item(s). If the resource_id is not given, all items of the given type are retrieved.a resource object, i.e. a
MaintainableArtefact: resource_type and resource_id are determined by the object’s class andidattribute, respectively.
Data is retrieved with resource_type=’data’. In this case, the optional keyword argument key can be used to constrain the data that is retrieved. Examples of the formats for key:
{'GEO': ['EL', 'ES', 'IE']}:dictwith dimension name(s) mapped to an iterable of allowable values.{'GEO': 'EL+ES+IE'}:dictwith dimension name(s) mapped to strings joining allowable values with ‘+’, the logical ‘or’ operator for SDMX web services.'....EL+ES+IE':strin which ordered dimension values (some empty,'') are joined with'.'. Using this form requires knowledge of the dimension order in the target data resource_id; in the example, dimension ‘GEO’ is the fifth of five dimensions:'.'.join(['', '', '', '', 'EL+ES+IE']).CubeRegion.to_query_string()can also be used to create properly formatted strings.
For formats 1 and 2, but not 3, the key argument is validated against the relevant
DSD, either given with the dsd keyword argument, or retrieved from the web service before the main query.For the optional param keyword argument, some useful parameters are:
‘startperiod’, ‘endperiod’: restrict the time range of data to retrieve.
‘references’: control which item(s) related to a metadata resource are retrieved, e.g. references=’parentsandsiblings’.
- Parameters:
resource_type (
strorResource, optional) – Type of resource to retrieve.resource_id (
str, optional) – ID of the resource to retrieve.tofile (
strorPathLikeor file-like object, optional) – File path or file-like to write SDMX data as it is received.use_cache (
bool, optional) – IfTrue, return a previously retrievedMessagefromcache, or update the cache with a newly-retrieved Message.dry_run (
bool, optional) – IfTrue, prepare and return arequests.Requestobject, but do not execute the query. The prepared URL and headers can be examined by inspecting the returned object.**kwargs – Other, optional parameters (below).
dsd (
DataStructureDefinition) – Existing object used to validate the key argument. If not provided, an additional query executed to retrieve a DSD in order to validate the key.force (
bool) – IfTrue, execute the query even if thesourcedoes not support queries for the given resource_type. Default:False.headers (
dict) – HTTP headers. Given headers will overwrite instance-wide headers passed to the constructor. Default:Noneto use the default headers of thesource.key (
strordict) – For queries with resource_type=’data’.strvalues are not validated;dictvalues are validated usingmake_constraint().params (
dict) – Query parameters. The SDMX REST web service guidelines describe parameters and allowable values for different queries. params is not validated before the query is executed.provider (
str) –ID of the agency providing the data or metadata. Default: ID of the
sourceagency.An SDMX web service is a ‘data source’ operated by a specific, ‘source’ agency. A web service may host data or metadata originally published by one or more ‘provider’ agencies. Many sources are also providers. Other agencies—e.g. the SDMX Global Registry—simply aggregate (meta)data from other providers, but do not provide any (meta)data themselves.
resource (
MaintainableArtefactsubclass) – Object to retrieve. If given, resource_type and resource_id are ignored.version (
str) –version>of a resource to retrieve. Default: the keyword ‘latest’.
- Returns:
The requested SDMX message or, if dry_run is
True, the prepared request object.- Return type:
- Raises:
NotImplementedError – If the
sourcedoes not support the given resource_type and force is notTrue.
- preview_data(flow_id, key={})[source]¶
Return a preview of data.
For the Dataflow flow_id, return all series keys matching key. Uses a feature supported by some data providers that returns
SeriesKeyswithout the correspondingObservations.To count the number of series:
keys = sdmx.Client('PROVIDER').preview_data('flow') len(keys)
To get a
pandasobject containing the key values:keys_df = sdmx.to_pandas(keys)
- Parameters:
- Return type:
- source: sdmx.source.Source[source]¶
source.Sourcefor requests sent from the instance.
- sdmx.Request(*args, **kwargs)[source]¶
Compatibility function for
Client.Added in version 2.0.
Deprecated since version 2.0: Will be removed in
sdmxversion 3.0.
- class sdmx.Resource(*values)[source]¶
Enumeration of SDMX-REST API resources.
This class merges the “resources” defined in Section V of the SDMX 2.1 and 3.0 standards; in the latter, only five values (availability, data, metadata, schema, structure) are used as the first part of a URL path; however, the choice of this first part and allowable query parameters depend on the more detailed list.
Enummembersdmx.modelclassactualconstraintagencyschemeallowedconstraintattachementconstraintAttachmentConstraintavailableconstraintcategorisationcategoryschemecodelistconceptschemecontentconstraintcustomtypeschemedatadataflowdataconsumerschemedataproviderschemedatastructurehierarchicalcodelistmetadatametadataflowmetadatastructurenamepersonalisationschemeorganisationschemeprovisionagreementrulesetschemestructureMixed.
structuresettransformationschemeuserdefinedoperatorschemeUserdefinedoperatorScheme.vtlmappingschemeorganisationunitschemeNot implemented.
processNot implemented.
reportingtaxonomyNot implemented.
schemaNot implemented.
- classmethod class_name(value: Resource, default=None) str[source]¶
Return the name of a
sdmx.modelclass from an enum value.Values are returned in lower case.
- sdmx.add_source(info: dict | str, id: str | None = None, override: bool = False, **kwargs) None[source]¶
Add a new data source.
The info expected is in JSON format:
{ "id": "ESTAT", "documentation": "http://data.un.org/Host.aspx?Content=API", "url": "http://ec.europa.eu/eurostat/SDMX/diss-web/rest", "name": "Eurostat", "supports": {"codelist": false, "preview": true} }
…with unspecified values using the defaults; see
Source.- Parameters:
info (
dict-like) – String containing JSON information about a data source.id (
str) – Identifier for the new datasource. IfNone(default), then info[‘id’] is used.override (
bool) – IfTrue, replace any existing data source with id. Otherwise, raiseValueError.**kwargs – Optional callbacks for handle_response and finish_message hooks.
- sdmx.get_source(id: str) Source[source]¶
Return the Source with the given id.
id is matched case-insensitively.
- sdmx.install_schemas(schema_dir: Path | None = None, version: str | Version = Version.2.1) Path[source]¶
Install SDMX-ML XML Schema documents for use with
validate_xml().- Parameters:
schema_dir (
Path, optional) – The directory where XSD schemas will be downloaded to. Default: a subdirectory namedsdmx/versionwithin theplatformdirs.user_cache_path().version (
strorVersion, optional) – The SDMX-ML schema version to install. One ofVersion["2.1"](default),Version["3.0.0"], orstrequivalent.
- Returns:
The path containing the installed schemas. If schema_dir is given, the return value is identical to the parameter.
- Return type:
Path
- sdmx.list_sources()[source]¶
Return a sorted list of valid source IDs.
These can be used to create
Clientinstances.
- sdmx.read_sdmx(filename_or_obj: bytes | str | Path | io.IOBase | io.BufferedReader, format: str | None = None, **kwargs) sdmx.message.Message[source]¶
Read a
Messagefrom a path, file, or stream in an SDMX standard format.To identify whether filename_or_obj contains SDMX-CSV, SDMX-JSON, or SDMX-ML,
BaseReader.handles()is called.- Parameters:
filename_or_obj –
may include:
strorpathlib.Path: path to a particular file.bytes: raw/binary SDMX content.io.IOBase: a buffer, opened file, or other I/O object containing binary SDMX content.
format (
'CSV','XML', or'JSON', optional) – force handling filename_or_obj as if it had the given extension, even ifhandles()fails to match.structure –
Structure,StructureUsage, or other information used by aBaseReaderto interpret the content of filename_or_obj. For example, theDataStructureDefinitionfor a structure-specific SDMX-ML message.
- sdmx.to_csv(obj: DataMessage | BaseDataSet, *, path: PathLike | None = None, rtype: type[str | DataFrame] = <class 'str'>, **kwargs) None | str | DataFrame[source]¶
Convert an SDMX obj to SDMX-CSV.
With
rtype=pandas.DataFrame, the returned object is not necessarily valid SDMX-CSV. In particular, writing this to file usingpandas.DataFrame.to_csv()will yield invalid SDMX-CSV, because pandas includes a CSV column corresponding to the index of the data frame. You must passindex=Falseto disable this behaviour. Withrtype=stror when giving path, this is done automatically.- Parameters:
path (
os.PathLike, optional) – Path to write an SDMX-CSV file.rtype – Return type; see below. Pass literally
strorpandas.DataFrame; not an instance of either class.kwargs – Keyword arguments passed to
PandasConverterandformat.csv.v1.FormatOptions.
- Returns:
- Raises:
NotImplementedError – If obj is any class except
DataSet; this is the only class for which the SDMX-CSV standard describes a format. The two optional parameters are exactly as described in the specification. Because SDMX-CSV includes a column with an identifier (partial URN) for the dataflow to which the data belong (the column is named differently according to format version; see SDMX-CSV), it is mandatory that theDataSet.described_byattribute of obj gives an association to an object from which aURNcan be constructed.NotImplementedError – if the kwargs include
labels="name"ortime_format="normalized".ValueError – If
DataSet.described_byisNone.
See also
- sdmx.to_pandas(obj, **kwargs)[source]¶
Convert an SDMX obj to
pandasobject(s).kwargs can include any of the attributes of
PandasConverter.Changed in version 1.0:
to_pandas()handles all types of objects, replacing the earlier, separatedata2pandasandstructure2pdwriters.Changed in version 2.23.0:
to_pandas()is a thin wrapper forPandasConverter.- Parameters:
format_options – if not given, an instance of
CSVFormatOptionsis used as a default.labels – if given, the
CSVFormatOptions.labelsattribute of the format_options keyword argument is replaced.time_format – if given, the
CSVFormatOptions.time_formatattribute of the format_options keyword argument is replaced.
- sdmx.to_sdmx(data, **kwargs) sdmx.message.Message[source]¶
Convert data in non-SDMX formats and data structures to SDMX
Message.Unlike
read_sdmx(), which handles only the standard SDMX formats SDMX-CSV, SDMX-JSON, and SDMX-ML, this method can will process any Python data structure handled by a knownCONVERTER.
- sdmx.to_xml(obj, **kwargs)[source]¶
Convert an SDMX obj to SDMX-ML.
- Parameters:
kwargs – Passed to
lxml.etree.to_string(), e.g. pretty_print =True.- Raises:
NotImplementedError – If writing specific objects to SDMX-ML has not been implemented in
sdmx.
- sdmx.validate_xml(msg: Path | IO, schema_dir: Path | None = None, version: str | Version = Version.2.1, max_errors: int = -1) bool[source]¶
Validate SDMX-ML in msg against the XML Schema (XSD) documents.
A log message with level
logging.ERRORis emitted if validation fails. This indicates the first (possibly not only) element in msg that is not valid per the schemas.- Parameters:
msg – Path or io-like containing an SDMX-ML message.
schema_dir – Directory with SDMX-ML XSD schemas used to validate the message.
version – The SDMX-ML schema version to validate against. One of
2.1or3.0.max_errors – Maximum number of messages to log on validation failure.
- Returns:
- Return type:
- Raises:
FileNotFoundError – if schema_dir (or a subdirectory) does not contain
SDMXMessage.xsd. Usesdmx.install_schemas()to download the schema files.NotImplementedError – if msg contains valid XML, but with a root element that is not part of the SDMX-ML standard.
compare: Compare SDMX artefacts¶
Compare SDMX artefacts.
- class sdmx.compare.Comparable[source]¶
Bases:
objectMix-in class for objects with a
compare()method.
- class sdmx.compare.Options(base: Any, allow_implied_urn: bool = True, strict: bool = True, log_level: int = 0, verbose: bool = False, _memo_key: tuple[int, int] = (0, 0))[source]¶
Bases:
objectOptions for a comparison.
- allow_implied_urn: bool = True[source]¶
Objects compare equal even if
IdentifiableArtefact.urnisNonefor either or both, so long as the URNs implied by their other attributes—that is, returned bysdmx.urn.make()—are the same.
- base: Any[source]¶
Base object for a recursive comparison. Used internally for memoization/to improve performance.
- log(message: str, level: int = 20) None[source]¶
Log message on level.
level must be at least
log_level.
- strict: bool = True[source]¶
if
True(the default), then attributes and associated objects must compare exactly equal. IfFalse, thenNonevalues on either side are permitted.- Type:
Strict comparison
- sdmx.compare.compare(left: object, right, opts: Options, context: str = '') bool[source]¶
- sdmx.compare.compare(left: int | str | date, right, opts, context='')
- sdmx.compare.compare(left: int | str | date, right, opts, context='')
- sdmx.compare.compare(left: int | str | date, right, opts, context='')
- sdmx.compare.compare(left: None | bool | float | type | Enum, right, opts, context)
- sdmx.compare.compare(left: None | bool | float | type | Enum, right, opts, context)
- sdmx.compare.compare(left: None | bool | float | type | Enum, right, opts, context)
- sdmx.compare.compare(left: None | bool | float | type | Enum, right, opts, context)
- sdmx.compare.compare(left: None | bool | float | type | Enum, right, opts, context)
- sdmx.compare.compare(left: dict, right, opts, context='')
- sdmx.compare.compare(left: list | set, right, opts, context='')
- sdmx.compare.compare(left: list | set, right, opts, context='')
- sdmx.compare.compare(left: _Element, right, opts, context='')
- sdmx.compare.compare(left: InternationalString, right, opts, context='')
Compare left to right.
Todo
Reimplement as a subclass of
common.DispatchConverter.
message: SDMX messages¶
Classes for SDMX messages.
Message and related classes are not defined in the SDMX
information model, but in the SDMX-ML standard.
sdmx also uses DataMessage to encapsulate SDMX-JSON data returned by
data sources.
- class sdmx.message.DataMessage(version: Version = Version.2.1, header: Header = <factory>, footer: Footer | None = None, response: requests.Response | None = None, data: list[BaseDataSet] = <factory>, dataflow: BaseDataflow | None = None, observation_dimension: _AllDimensions | DimensionComponent | list[DimensionComponent] | None = None)[source]¶
Bases:
MessageSDMX Data Message.
Note
A DataMessage may contain zero or more
DataSet, sodatais a list. To retrieve the first (and possibly only) data set in the message, access the first element of the list:msg.data[0].- dataflow: BaseDataflow | None = None[source]¶
DataflowDefinitionthat contains the data.
- observation_dimension: _AllDimensions | DimensionComponent | list[DimensionComponent] | None = None[source]¶
The “dimension at observation level”.
- property structure_type: type[Structure][source]¶
Structuresubtype describing the contained (meta)data.
- update() None[source]¶
Update
observation_dimension.The observation dimensions (or dimension observation) is determined automatically if:
There is at least 1
DataSetin the message.For at least 1 data set:
structured_byis defined.There is at least 1
Observationin the data set. (update()checks only the first observation.)The
Observation.dimensionis aKeyreferring to exactly 1 dimension.
The dimension indicated by (2) is the same for all DataSets in the message.
If not all these conditions are met, messages are logged with level DEBUG, and
observation_dimensionis set toNone.
- class sdmx.message.ErrorMessage(version: Version = Version.2.1, header: Header = <factory>, footer: Footer | None = None, response: requests.Response | None = None)[source]¶
Bases:
Message
Bases:
ComparableFooter of an SDMX-ML message.
SDMX-JSON messages do not have footers.
The body text of the Footer contains zero or more blocks of text.
- class sdmx.message.Header(error: str | None = None, extracted: datetime | None = None, id: str | None = None, prepared: datetime | None = None, reporting_begin: datetime | None = None, reporting_end: datetime | None = None, receiver: Agency | None = None, sender: Agency | None = None, source: InternationalStringDescriptor = None, test: bool = False)[source]¶
Bases:
objectHeader of an SDMX-ML message.
SDMX-JSON messages do not have headers.
- receiver: Agency | None = None[source]¶
Intended recipient of the message, e.g. the user’s name for an authenticated service.
- reporting_begin: datetime | None = None[source]¶
Start of the time period covered by a
DataMessage.
- reporting_end: datetime | None = None[source]¶
End of the time period covered by a
DataMessage.
- source: InternationalStringDescriptor = None[source]¶
- class sdmx.message.Message(version: sdmx.format.Version = <Version.2.1: 2.1>, header: sdmx.message.Header = <factory>, footer: sdmx.message.Footer | None = None, response: 'requests.Response | None' = None)[source]¶
Bases:
Comparable(optional)
Footerinstance.
- response: requests.Response | None = None[source]¶
requests.Responseinstance for the response to the HTTP request that returned the Message. This is not part of the SDMX standard.
- class sdmx.message.MetadataMessage(version: Version = Version.2.1, header: Header = <factory>, footer: Footer | None = None, response: requests.Response | None = None, data: list[BaseDataSet] = <factory>, dataflow: BaseDataflow | None = None, observation_dimension: _AllDimensions | DimensionComponent | list[DimensionComponent] | None = None)[source]¶
Bases:
DataMessageSDMX Metadata Message.
- class sdmx.message.RegistryInterface(version: Version = Version.2.1, header: Header = <factory>, footer: Footer | None = None, response: requests.Response | None = None)[source]¶
Bases:
MessageCommon base class for registry interface messages.
- class sdmx.message.StructureMessage(version: Version = Version.2.1, header: Header = <factory>, footer: Footer | None = None, response: requests.Response | None = None, categorisation: DictLikeDescriptor[str, ~sdmx.model.common.Categorisation]=None, category_scheme: DictLikeDescriptor[str, ~sdmx.model.common.CategoryScheme]=None, codelist: DictLikeDescriptor[str, ~sdmx.model.common.Codelist]=None, concept_scheme: DictLikeDescriptor[str, ~sdmx.model.common.ConceptScheme]=None, constraint: DictLikeDescriptor[str, ~sdmx.model.common.BaseConstraint]=None, custom_type_scheme: DictLikeDescriptor[str, ~sdmx.model.common.CustomTypeScheme]=None, dataflow: DictLikeDescriptor[str, ~sdmx.model.common.BaseDataflow]=None, hierarchical_codelist: DictLikeDescriptor[str, ~sdmx.model.v21.HierarchicalCodelist]=None, hierarchy: DictLikeDescriptor[str, ~sdmx.model.v30.Hierarchy]=None, metadataflow: DictLikeDescriptor[str, ~sdmx.model.common.BaseMetadataflow]=None, metadatastructure: DictLikeDescriptor[str, ~sdmx.model.common.BaseMetadataStructureDefinition]=None, name_personalisation_scheme: DictLikeDescriptor[str, ~sdmx.model.common.NamePersonalisationScheme]=None, organisation_scheme: DictLikeDescriptor[str, ~sdmx.model.common.OrganisationScheme]=None, provisionagreement: DictLikeDescriptor[str, ~sdmx.model.common.ProvisionAgreement]=None, ruleset_scheme: DictLikeDescriptor[str, ~sdmx.model.common.RulesetScheme]=None, structure: DictLikeDescriptor[str, ~sdmx.model.common.BaseDataStructureDefinition]=None, structureset: DictLikeDescriptor[str, ~sdmx.model.v21.StructureSet]=None, transformation_scheme: DictLikeDescriptor[str, ~sdmx.model.common.TransformationScheme]=None, user_defined_operator_scheme: DictLikeDescriptor[str, ~sdmx.model.common.UserDefinedOperatorScheme]=None, valuelist: DictLikeDescriptor[str, ~sdmx.model.v30.ValueList]=None, vtl_mapping_scheme: DictLikeDescriptor[str, ~sdmx.model.common.VTLMappingScheme]=None)[source]¶
Bases:
MessageSDMX StructureMessage.
- add(obj: IdentifiableArtefact)[source]¶
Add obj to the StructureMessage.
- categorisation: DictLikeDescriptor[str, Categorisation] = None[source]¶
Collection of
Categorisation.
- category_scheme: DictLikeDescriptor[str, CategoryScheme] = None[source]¶
Collection of
CategoryScheme.
- concept_scheme: DictLikeDescriptor[str, ConceptScheme] = None[source]¶
Collection of
ConceptScheme.
- constraint: DictLikeDescriptor[str, BaseConstraint] = None[source]¶
Collection of
ContentConstraint.
- custom_type_scheme: DictLikeDescriptor[str, CustomTypeScheme] = None[source]¶
Collection of
CustomTypeScheme.
- dataflow: DictLikeDescriptor[str, BaseDataflow] = None[source]¶
Collection of
Dataflow(Definition).
- get(obj_or_id: str | IdentifiableArtefact) IdentifiableArtefact | None[source]¶
Retrieve obj_or_id from the StructureMessage.
- Parameters:
obj_or_id (
strorIdentifiableArtefact) –if an IdentifiableArtefact, return an object of the same class and
id.if
str, this may be:An exact match for some
IdentifiableArtefact.id.Part of an SDMX
URN, for instance “FOO(1.2.3)”, “MAINT:FOO”, or “MAINT:FOO(1.2.3)”.A full SDMX
URN.
- Returns:
with the given ID and possibly class, or
Noneif there is no match.- Return type:
- Raises:
ValueError – if there are ≥2 objects with the same obj_or_id; for instance, two objects of different classes, or two objects of the same class with different
maintainerorversion.
- hierarchical_codelist: DictLikeDescriptor[str, HierarchicalCodelist] = None[source]¶
Collection of
HierarchicalCodelist.
- hierarchy: DictLikeDescriptor[str, Hierarchy] = None[source]¶
Collection of
v30.Hierarchy.
- iter_objects(external_reference: bool = True) Generator[MaintainableArtefact, None, None][source]¶
Iterate over all objects in the message.
- metadataflow: DictLikeDescriptor[str, BaseMetadataflow] = None[source]¶
Collection of
Metadataflow(Definition).
- metadatastructure: DictLikeDescriptor[str, BaseMetadataStructureDefinition] = None[source]¶
MetadataStructureDefinition <.BaseMetadataStructureDefinition>.
- Type:
Collection of
- Type:
class
- name_personalisation_scheme: DictLikeDescriptor[str, NamePersonalisationScheme] = None[source]¶
Collection of
NamePersonalisationScheme.
- objects(cls)[source]¶
Get a reference to the attribute for objects of type cls.
For example, if cls is the class
DataStructureDefinition(not an instance), return a reference tostructure.
- organisation_scheme: DictLikeDescriptor[str, OrganisationScheme] = None[source]¶
Collection of
OrganisationScheme.
- provisionagreement: DictLikeDescriptor[str, ProvisionAgreement] = None[source]¶
Collection of
ProvisionAgreement.
- ruleset_scheme: DictLikeDescriptor[str, RulesetScheme] = None[source]¶
Collection of
RulesetScheme.
- structure: DictLikeDescriptor[str, BaseDataStructureDefinition] = None[source]¶
Collection of
DataStructureDefinition.
- structureset: DictLikeDescriptor[str, StructureSet] = None[source]¶
Collection of
StructureSet.
- transformation_scheme: DictLikeDescriptor[str, TransformationScheme] = None[source]¶
Collection of
TransformationScheme.
- user_defined_operator_scheme: DictLikeDescriptor[str, UserDefinedOperatorScheme] = None[source]¶
Collection of
UserDefinedOperatorScheme.
- valuelist: DictLikeDescriptor[str, ValueList] = None[source]¶
Collection of
ValueList(SDMX 3.0 only).
- vtl_mapping_scheme: DictLikeDescriptor[str, VTLMappingScheme] = None[source]¶
Collection of
VTLMappingScheme.
- class sdmx.message.SubmitStructureResponse(version: Version = Version.2.1, header: Header = <factory>, footer: Footer | None = None, response: requests.Response | None = None, result: list[SubmissionResult] = <factory>)[source]¶
Bases:
RegistryInterfaceSDMX SubmitStructureResponse.
- result: list[SubmissionResult][source]¶
rest: SDMX-REST standard¶
- class sdmx.rest.URL(source: sdmx.source.Source, resource_type: Resource, **kwargs)[source]¶
Bases:
URLUtility class to build SDMX-REST API v1.5.0 URLs.
- handle_metadata()[source]¶
Handle URL parameters for metadata endpoints.
- Raises:
NotImplementedError – Although it is described in the standards, there are no known SDMX REST data sources that support this API endpoint to confirm behaviour. If you are aware of one, please open an issue.
- handle_registration()[source]¶
Handle URL parameters for registration endpoints.
- Raises:
ValueError – Always. This type of query is not included in SDMX-REST v1.5.0.
- handle_structure()[source]¶
Handle URL parameters for structure endpoints.
Warning
This method currently preserves the behaviour of
Client.get()as ofsdmxversion 2.13.1 and earlier. Namely, defaults are supplied for the?references=…query parameter in the following cases:Resource.datafloworResource.datastructureand a specificresource_idis given (that is, not “all”) → default?references=all.Resource.categoryscheme→ default?references=parentsandsiblings.
These differ from the SDMX-REST v1.5.0 standard, which states the default should be
nonein all cases. Thesdmx-specific defaults may be deprecated and removed in future versions; to ensure stable behaviour, give the parameter explicitly.
rest.v21¶
SDMX-REST API v1.5.0.
Note that version 1.5.0 of the REST API corresponds to version 2.1 of the overall SDMX standards. See the documentation and OpenAPI specification for further details.
- sdmx.rest.v21.PARAM: dict[str, Parameter] = {'component_id': OptionalPath(name='component_id', values=set(), default=None), 'context': PathParameter(name='context', values={'metadatastructure', 'dataflow', 'provisionagreement', 'metadataflow', 'datastructure'}, default=None), 'detail_d': QueryParameter(name='detail', values={'full', 'dataonly', 'nodata', 'serieskeysonly'}, default=None), 'detail_s': QueryParameter(name='detail', values={'full', 'allstubs', 'referencepartial', 'referencecompletestubs', 'referencestubs', 'allcompletestubs'}, default=None), 'end_period': QueryParameter(name='end_period', values=set(), default=None), 'explicit_measure': QueryParameter(name='explicit_measure', values={False, True}, default=None), 'flow': OptionalPath(name='resource_id', values=set(), default=None), 'provider': OptionalPath(name='provider', values=set(), default=None), 'references_s': QueryParameter(name='references', values={'descendants', <Resource.attachementconstraint: 'attachementconstraint'>, <Resource.structureset: 'structureset'>, <Resource.customtypescheme: 'customtypescheme'>, <Resource.namepersonalisationscheme: 'namepersonalisationscheme'>, <Resource.schema: 'schema'>, <Resource.metadataflow: 'metadataflow'>, <Resource.contentconstraint: 'contentconstraint'>, <Resource.agencyscheme: 'agencyscheme'>, <Resource.datastructure: 'datastructure'>, <Resource.userdefinedoperatorscheme: 'userdefinedoperatorscheme'>, <Resource.reportingtaxonomy: 'reportingtaxonomy'>, 'children', <Resource.provisionagreement: 'provisionagreement'>, <Resource.dataflow: 'dataflow'>, <Resource.rulesetscheme: 'rulesetscheme'>, <Resource.organisationunitscheme: 'organisationunitscheme'>, <Resource.categorisation: 'categorisation'>, <Resource.hierarchicalcodelist: 'hierarchicalcodelist'>, <Resource.availableconstraint: 'availableconstraint'>, <Resource.transformationscheme: 'transformationscheme'>, <Resource.dataconsumerscheme: 'dataconsumerscheme'>, 'all', <Resource.actualconstraint: 'actualconstraint'>, <Resource.metadatastructure: 'metadatastructure'>, <Resource.registration: 'registration'>, 'parentsandsiblings', <Resource.data: 'data'>, <Resource.vtlmappingscheme: 'vtlmappingscheme'>, <Resource.organisationscheme: 'organisationscheme'>, <Resource.structure: 'structure'>, <Resource.categoryscheme: 'categoryscheme'>, 'parents', <Resource.dataproviderscheme: 'dataproviderscheme'>, <Resource.codelist: 'codelist'>, <Resource.conceptscheme: 'conceptscheme'>, <Resource.process: 'process'>, <Resource.allowedconstraint: 'allowedconstraint'>, <Resource.metadata: 'metadata'>, 'none'}, default=None), 'start_period': QueryParameter(name='start_period', values=set(), default=None), 'version': PathParameter(name='version', values=set(), default='latest')}[source]¶
v1.5.0-specific path and query parameters.
- class sdmx.rest.v21.URL(source: sdmx.source.Source, resource_type: Resource, **kwargs)[source]¶
Bases:
URLUtility class to build SDMX-REST API v1.5.0 URLs.
- handle_metadata()[source]¶
Handle URL parameters for metadata endpoints.
- Raises:
Although it is described in the standards, there are no known SDMX REST data sources that support this API endpoint to confirm behaviour. If you are aware of one, please open an issue.
- handle_registration()[source]¶
Handle URL parameters for registration endpoints.
- Raises:
ValueError – Always. This type of query is not included in SDMX-REST v1.5.0.
- handle_structure()[source]¶
Handle URL parameters for structure endpoints.
Warning
This method currently preserves the behaviour of
Client.get()as ofsdmxversion 2.13.1 and earlier. Namely, defaults are supplied for the?references=…query parameter in the following cases:Resource.datafloworResource.datastructureand a specificresource_idis given (that is, not “all”) → default?references=all.Resource.categoryscheme→ default?references=parentsandsiblings.
These differ from the SDMX-REST v1.5.0 standard, which states the default should be
nonein all cases. Thesdmx-specific defaults may be deprecated and removed in future versions; to ensure stable behaviour, give the parameter explicitly.
rest.v30¶
SDMX-REST API v2.1.0.
Note that version 2.1.0 of the REST API corresponds to version 3.0.0 of the overall SDMX standards. See the documentation and OpenAPI specification for further details.
- sdmx.rest.v30.PARAM: dict[str, Parameter] = {'attributes': QueryParameter(name='attributes', values=set(), default=None), 'c': QueryParameter(name='c', values=set(), default=None), 'component_id': PathParameter(name='component_id', values=set(), default=None), 'context': PathParameter(name='context', values={'metadatastructure', 'dataflow', 'provisionagreement', 'metadataflow', 'datastructure', 'metadataprovisionagreement'}, default=None), 'context_d': PathParameter(name='context', values={'*', 'datastructure', 'dataflow', 'provisionagreement'}, default='*'), 'detail_m': QueryParameter(name='detail', values={'full', 'allstubs'}, default=None), 'detail_s': QueryParameter(name='detail', values={'full', 'allstubs', 'referencepartial', 'raw', 'referencecompletestubs', 'referencestubs', 'allcompletestubs'}, default=None), 'measures': QueryParameter(name='measures', values=set(), default=None), 'provider_id': PathParameter(name='provider_id', values=set(), default='*'), 'references_s': QueryParameter(name='references', values={'descendants', <Resource.attachementconstraint: 'attachementconstraint'>, <Resource.structureset: 'structureset'>, <Resource.customtypescheme: 'customtypescheme'>, <Resource.namepersonalisationscheme: 'namepersonalisationscheme'>, <Resource.schema: 'schema'>, <Resource.metadataflow: 'metadataflow'>, <Resource.contentconstraint: 'contentconstraint'>, <Resource.agencyscheme: 'agencyscheme'>, <Resource.datastructure: 'datastructure'>, <Resource.userdefinedoperatorscheme: 'userdefinedoperatorscheme'>, <Resource.reportingtaxonomy: 'reportingtaxonomy'>, 'children', <Resource.provisionagreement: 'provisionagreement'>, <Resource.dataflow: 'dataflow'>, <Resource.rulesetscheme: 'rulesetscheme'>, <Resource.organisationunitscheme: 'organisationunitscheme'>, <Resource.categorisation: 'categorisation'>, <Resource.hierarchicalcodelist: 'hierarchicalcodelist'>, <Resource.availableconstraint: 'availableconstraint'>, <Resource.transformationscheme: 'transformationscheme'>, <Resource.dataconsumerscheme: 'dataconsumerscheme'>, 'all', <Resource.actualconstraint: 'actualconstraint'>, <Resource.metadatastructure: 'metadatastructure'>, <Resource.registration: 'registration'>, 'parentsandsiblings', <Resource.data: 'data'>, <Resource.vtlmappingscheme: 'vtlmappingscheme'>, <Resource.organisationscheme: 'organisationscheme'>, <Resource.structure: 'structure'>, <Resource.categoryscheme: 'categoryscheme'>, 'parents', <Resource.dataproviderscheme: 'dataproviderscheme'>, 'ancestors', <Resource.codelist: 'codelist'>, <Resource.conceptscheme: 'conceptscheme'>, <Resource.process: 'process'>, <Resource.allowedconstraint: 'allowedconstraint'>, <Resource.metadata: 'metadata'>, 'none'}, default=None), 'resource_id': PathParameter(name='resource_id', values=set(), default='*'), 'updated_after': QueryParameter(name='update_after', values=set(), default=None), 'updated_before': QueryParameter(name='update_before', values=set(), default=None), 'version': PathParameter(name='version', values=set(), default='+')}[source]¶
SDMX-REST v2.1.0-specific path and query parameters.
- class sdmx.rest.v30.URL(source: sdmx.source.Source, resource_type: Resource, **kwargs)[source]¶
Bases:
URLUtility class to build SDMX-REST API v2.1.0 URLs.
session: HTTP sessions and responses¶
- class sdmx.session.ResponseIO(response, tee: IO | os.PathLike | None = None)[source]¶
Buffered wrapper for
requests.Responsewith optional file output.ResponseIOwraps arequests.Responseobject’s ‘content’ attribute, providing a file-like object from which bytes can beread()incrementally.- Parameters:
response (
requests.Response) – HTTP response to wrap.tee (
binary,writable :py:class:`io.BufferedIOBase`,defaultstoio.BytesIO()) – tee is exposed as self.tee and not closed explicitly.
- class sdmx.session.Session(timeout: float = 30.0, **kwargs)[source]¶
requests.Sessionwith optional caching.If
requests_cacheis installed, this class inherits fromCacheMixinand caches responses. Otherwise, it inherits only from therequests_cache.- Parameters:
timeout (
float) – Timeout in seconds, used for every request.kwargs –
These may include:
Values for any attributes of
requests.Session, such asproxies,stream, orverify. These are set on the created Session.Keyword arguments to
CacheMixinor anyrequests_cachebackend. Note that:Unlike
requests_cache, you must supplybackend="sqlite"explicitly; otherwisesdmxusesbackend="memory".These classes will silently ignore any other/unrecognized keyword arguments.
- Raises:
TypeError – if
requests_cacheis not installed and any parameters are passed except for timeout.
urn: Uniform Resource Names (URNs) for SDMX objects¶
- class sdmx.urn.URN(value: dataclasses.InitVar[str | None] = None, package: str = '', klass: str = '', agency: str = '', id: str = '', version: str = '', item_id: str = '')[source]¶
SDMX Uniform Resource Name (URN).
- agency: str[source]¶
ID of the
Agencythat is theMaintainableArtefact.maintainer.
- id: str[source]¶
ID of the
MaintainableArtefact.
- value: dataclasses.InitVar[str | None] = None[source]¶
Existing URN to parse, for example “urn:sdmx:org.sdmx.infomodel.codelist.Code=BAZ:FOO(1.2.3).BAR”. The maintainer ID (“BAZ”) and version (“1.2.3”) must refer to a
MaintainableArtefact. If (as in this example) the URN is for a non-maintainable child (for example, aItemin aItemScheme), these are the maintainer ID and version of the containing scheme/other maintainable parent object.
- version: str[source]¶
VersionableArtefact.versionof the maintainable artefact.parent.
- sdmx.urn.expand(value: str) str[source]¶
Return the full URN for value.
Example
>>> expand("Code=BAZ:FOO(1.2.3).BAR") "urn:sdmx:org.sdmx.infomodel.codelist.Code=BAZ:FOO(1.2.3).BAR"
- sdmx.urn.make(obj, maintainable_parent: MaintainableArtefact | None = None, strict: bool = False, **kwargs) str[source]¶
Create an SDMX URN for obj.
If obj is not
MaintainableArtefact, then maintainable_parent must be supplied in order to construct the URN. If kwargs are supplied, they must be fields/attributes ofURN, and override values derived from obj and/or maintainable_parent.- Returns:
String representation of the URN.
- Return type:
- sdmx.urn.match(value: str) dict[str, str][source]¶
Match
URNin value, returning adictwith the match groups.Example
>>> match("urn:sdmx:org.sdmx.infomodel.codelist.Code=BAZ:FOO(1.2.3).BAR") { "package": "codelist", "class": "Code", "agency": "BAZ", "id": "FOO", "version": "1.2.3", "item_id": "BAR", }
- Raises:
ValueError – If value is not a well-formed SDMX URN.
- sdmx.urn.normalize(value: str) str[source]¶
‘Normalize’ a URN.
Handle “…DataFlow=…” (SDMX 3.0) vs. “…DataFlowDefinition=…” (SDMX 2.1) in URNs; prefer the former.
Utilities and internals¶
- sdmx.tools.dimensions_to_attributes(ds: BaseDataSet, dim_ids: Collection[str]) None[source]¶
Mutate ds and the associated DSD, changing dimensions to attributes.
- sdmx.util.compare(attr, a, b, strict: bool) bool[source]¶
Return
Trueifa.attr==b.attr.If strict is
False,Noneis permissible as a or b; otherwise,Deprecated since version 2.23.0: Use
Comparable.compare()orcompare()instead.
- sdmx.util.direct_fields(cls) Iterable[Field][source]¶
Return the data class fields defined on cls or its class.
This is like the
__fields__attribute, but excludes the fields defined on any parent class(es).
- sdmx.util.parse_content_type(value: str) tuple[str, dict[str, Any]][source]¶
Return content type and parameters from value.
Modified from
requests.util.
- sdmx.util.preserve_dunders(cls: type, *names: str) Callable[[type], type][source]¶
Copy dunder names from cls to a decorated class.
- sdmx.util.ucfirst(value: str) str[source]¶
Return value with its first character transformed to upper-case.
- class sdmx.types.MaintainableArtefactArgs[source]¶
Bases:
VersionableArtefactArgs
DictLike collections¶
- class sdmx.dictlike.DictLike(*args, **kwargs)[source]¶
Bases:
dict,MutableMapping[KT,VT],ComparableContainer with features of
dict, attribute access, and validation.
Structure expressions in Item descriptions¶
Parse structure information from item description.
|
Parse the |
|
Parse a structure expression for the item in itemscheme with the given id. |
|
Parse structure expressions for every item in itemscheme. |
Note
The code in this module does not perform calculations or operations on data using the parsed structure expressions. User code should use the returned information to determine which operations should be performed.
- sdmx.util.item_structure.OPS = {'+': <built-in function add>, '-': <built-in function sub>, '=': <built-in function eq>}[source]¶
Operators understood by
parse_item_description()
- sdmx.util.item_structure.parse_all(itemscheme: ItemScheme, **kwargs) dict[str, list[tuple[Callable, Item | str]]][source]¶
Parse structure expressions for every item in itemscheme.
- Parameters:
kwargs – Passed to
parse_item_description()viaparse_item().- Returns:
Keys are references to the items of itemscheme. Values are the results of
parse_item(), i.e. possibly empty.- Return type:
dictof(Item → list)
- sdmx.util.item_structure.parse_item(itemscheme: ItemScheme, id=<class 'str'>, **kwargs) list[tuple[Callable, Item | str]][source]¶
Parse a structure expression for the item in itemscheme with the given id.
In addition to the behaviour of
parse_item_description(),parse_item()replaces—where possible—the operandstrIDs with references to specific otherItemsin the itemscheme.Where not possible, the operand is returned as-is. For example, in an expression like:
A = B + C - D (until 2022) - E
…
B,C, andEmay resolve to references to particular other items, while the string “D (until 2022)” will be returned as-is, and not further parsed as a reference to an item with IDD. (This functionality may be added in a future version ofsdmx.)- Parameters:
kwargs – Passed to
parse_item_description().- Returns:
Where possible, operand is a reference to an existing item in itemscheme; otherwise the same
stras returned byparse_item_description().- Return type:
- sdmx.util.item_structure.parse_item_description(item: Item, locale: str | None = None) list[tuple[Callable, str]][source]¶
Parse the
descriptionof item for a structure expression.A common—but non-standard—SDMX usage is that
ItemsinItemSchemescontain structure expressions in theirdescription. These may resemble:A = B + C - D
…indicating that data for
Acan be computed by adding data forBandCand subtracting data forD. In this usage,Amatches theIdentifiableArtefact.idof the item, andB,C, andDare usually the IDs of other Items in the same ItemScheme.Another form is:
B + C - D
In this case, the left-hand side and “=” are omitted.
parse_item_description()parses these expressions, returning a list of tuples. In each tuple, the first element gives the operation to be applied (in the above, examples, implicitlyadd()for “B”), and the second element is the ID of the operand.Other descriptions are not (yet) supported, including:
Multi-line descriptions, in which the structure expression occurs on one line.
Structure expressions that appear on lines with other text, for example:
Some text; A = B + C - D
- Parameters:
locale (
str) – Use thislocalizationof item’s description, instead of the default (DEFAULT_LOCALEor the sole localization).- Returns:
The list is empty if:
item has no
description.The description does not contain a structure expression.
An expression like “A = B + …” exists, but
Adoes not match the ID of item.
- Return type:
Example
>>> from sdmx.model.common import Code >>> from sdmx.util.item_structure import parse_item_description >>> c = Code(id="A", description="A = B + C - D") >>> parse_item_description(c) [(<function _operator.add(a, b, /)>, 'B'), (<function _operator.add(a, b, /)>, 'C'), (<function _operator.sub(a, b, /)>, 'D')]