calamus API

Schema

Marshmallow schema implementation that supports JSON-LD.

class calamus.schema.JsonLDAnnotation(name, bases, namespace, **kwargs)[source]

Meta-class allowing automated generation of calamus schema based on annotations.

Example:

import datetime.datetime as dt

from calamus import JsonLDAnnotation
import calamus.fields as fields

schema = fields.Namespace("http://schema.org/")

class User(metaclass=JsonLDAnnotation):
    class Meta:
        rdf_type = schema.Person
    _id = fields.Id()
    birth_date = fields.Date(schema.birthDate, load_default=dt.now)
    name = fields.String(schema.name, load_default=lambda: "John")

 user = User()

 # dumping
 User.schema().dump(user)
 # or
 user.dump()

 # loading
 u = User.schema().load({"_id": "http://example.com/user/1", "name": "Bill", "birth_date": "1970-01-01 00:00"})
class calamus.schema.JsonLDSchema(*args, only=None, exclude=(), many=False, context=None, load_only=(), dump_only=(), partial=False, unknown=None, flattened=False, lazy=False, _all_objects=None, _visited=None, _top_level=True)[source]

Schema for a JsonLD class.

Parameters
  • flattened (bool) – If the JSON-LD should be loaded/dumped in flattened form

  • lazy (bool) – Enables lazy loading of nested attributes

Example:

from calamus import JsonLDSchema
import calamus.fields as fields
from mymodels import User
schema = fields.Namespace("http://schema.org/")
class UserSchema(JsonLDSchema):
    class Meta:
        rdf_type = schema.Person
        model = User
    _id = fields.Id()
    birth_date = fields.Date(schema.birthDate)
    name = fields.String(schema.name)
OPTIONS_CLASS

alias of calamus.schema.JsonLDSchemaOpts

Get all objects pointing to the object in data with the field field_name.

Used for unflattening a list.

make_instance(data, **kwargs)[source]

Transform loaded dict into corresponding object.

validate_properties(data, ontology, return_valid_data=False, strict=False)[source]

Validate JSON-LD against an ontology.

Parameters
  • data (Union[object, dict, list]) – JSON-LD data or model (or list of them).

  • ontology (str) – Path/URI to an ontology file.

  • return_valid_data (bool) – Whether to delete invalid properties to return only valid data or else returns a dict containing valid and invalid properties, Default: False

class calamus.schema.JsonLDSchemaMeta(name, bases, attrs)[source]

Meta-class for a for a JsonLDSchema class.

class calamus.schema.JsonLDSchemaOpts(meta, *args, **kwargs)[source]

Options class for JsonLDSchema.

Adds the following options:
  • rdf_type: The RDF type(s) for this schema.

  • model: The python type this schema (de-)serializes.

  • add_value_types: Whether to add @type information to scalar field values.

  • id_generation_strategy: A callable(dict, obj) that generates an Id on the fly if none is set.

    With dict being the deserialized Json-LD dict and obj being the original object.

calamus.schema.blank_node_id_strategy(ret, obj)[source]

id_generation_strategy that creates random blank node ids.

Fields

Marshmallow fields for use with JSON-LD.

class calamus.fields.AwareDateTime(*args, **kwargs)[source]

A naive date/time field.

class calamus.fields.BlankNodeId(*args, **kwargs)[source]

A blank/anonymous node identifier.

property data_key

Return the (expanded) JsonLD field name.

class calamus.fields.Boolean(*args, **kwargs)[source]

A Boolean field.

class calamus.fields.Date(*args, **kwargs)[source]

A naive date/time field.

class calamus.fields.DateTime(*args, extra_formats=('%Y-%m-%d'), **kwargs)[source]

A date/time field.

class calamus.fields.Dict(field_name=None, *args, **kwargs)[source]

A dict field.

class calamus.fields.Float(*args, **kwargs)[source]

A float field.

class calamus.fields.IRI(*args, **kwargs)[source]

An external IRI reference.

class calamus.fields.IRIReference(namespace, name)[source]

Represent an IRI in a namespace.

Parameters
  • namespace (Namespace) – The Namespace this IRI is part of.

  • name (str) – the property name of this IRI.

class calamus.fields.Id(*args, **kwargs)[source]

A node identifier.

class calamus.fields.Integer(*args, **kwargs)[source]

An integer field.

class calamus.fields.List(*args, **kwargs)[source]

A potentially ordered list using the @list keyword.

Parameters

ordered (bool) – Whether this is an ordered (via @list keyword) list.

Warning: The JSON-LD flattening algorithm does not combine @list entries when merging nodes. So if you use ordered=True and flatten the output, and you have the node containing the list in multiple places in the graph, the node will get merged but its lists wont get merged (you get a list of lists instead), which means that the output can’t be deserialized back to python objects.

property opts

Return parent’s opts.

class calamus.fields.NaiveDateTime(*args, **kwargs)[source]

A naive date/time field.

class calamus.fields.Namespace(namespace, ontology=None)[source]

Represents a namespace/ontology.

Parameters
  • namespace (str) – The base namespace URI for this namespace.

  • ontology (str) – Path to an ontology(OWL) file for this namespace.

class calamus.fields.Nested(*args, **kwargs)[source]

A reference to one or more nested classes.

load_single_entry(value, partial)[source]

Loads a single nested entry from its schema.

property schema

The nested Schema object.

This method was copied from marshmallow and modified to support multiple different nested schemes.

class calamus.fields.Raw(field_name=None, *args, **kwargs)[source]

A raw field.

class calamus.fields.RawJsonLD(field_name=None, *args, **kwargs)[source]

A raw JSON-LD field.

class calamus.fields.String(*args, **kwargs)[source]

A string field.

class calamus.fields.Time(*args, **kwargs)[source]

A naive date/time field.

Utilities

Calamus utilities.

calamus.utils.normalize_id(id_object: Union[Mapping[str, Any], Iterable[Mapping[str, Any]], str])[source]

Turns a JsonLD id reference into normalized form (list of strings).

calamus.utils.normalize_type(type_data)[source]

Normalizes a JsonLD type reference as list of string.

calamus.utils.normalize_value(value)[source]

Normalizes a JsonLD value object to a simple value.

calamus.utils.validate_field_properties(data, ontology, query=None, mem={'invalid': {}, 'valid': {}})[source]

Validates if the field properties for data are present in the OWL ontology graph or not.

Parameters
  • data (dict) – The data to validate.

  • ontology (rdflib.Graph) – The OWL ontology graph to validate against.

  • query (rdflib.plugins.sparql.sparql.prepareQuery) – Optional prepared query (for performance reasons).

  • mem (dict) – memoization for repeated calls.

Returns

Key valid has all valid properties (excluding @id and @type), invalid has all invalid properties

Return type

dict