examples Package

These examples all live in ./examples in the source-distribution of RDFLib.

conjunctive_graphs Module

An RDFLib ConjunctiveGraph is an (unnamed) aggregation of all the Named Graphs within a Store. The get_context() method can be used to get a particular named graph for use, such as to add triples to, or the default graph can be used.

This example shows how to create Named Graphs and work with the conjunction (union) of all the graphs.

custom_datatype Module

RDFLib can map between RDF data-typed literals and Python objects.

Mapping for integers, floats, dateTimes, etc. are already added, but you can also add your own.

This example shows how rdflib.term.bind() lets you register new mappings between literal datatypes and Python objects

custom_eval Module

This example shows how a custom evaluation function can be added to handle certain SPARQL Algebra elements.

A custom function is added that adds rdfs:subClassOf “inference” when asking for rdf:type triples.

Here the custom eval function is added manually, normally you would use setuptools and entry_points to do it: i.e. in your setup.py:

entry_points = {
    'rdf.plugins.sparqleval': [
        'myfunc = mypackage:MyFunction',
        ],
}
examples.custom_eval.customEval(ctx, part)[source]

Rewrite triple patterns to get super-classes

foafpaths Module

SPARQL 1.1 defines path operators for combining/repeating predicates in triple-patterns.

We overload some Python operators on URIRefs to allow creating path operators directly in Python.

Operator

Path

p1 / p2

Path sequence

p1 | p2

Path alternative

p1 * '*'

chain of 0 or more p’s

p1 * '+'

chain of 1 or more p’s

p1 * '?'

0 or 1 p

~p1

p1 inverted, i.e. (s p1 o) <=> (o ~p1 s)

-p1

NOT p1, i.e. any property but p1

These can then be used in property position for s,p,o triple queries for any graph method.

See the docs for rdflib.paths for the details.

This example shows how to get the name of friends (i.e values two steps away x knows y, y name z) with a single query.

prepared_query Module

SPARQL Queries be prepared (i.e parsed and translated to SPARQL algebra) by the rdflib.plugins.sparql.prepareQuery() method.

initNs can be used instead of PREFIX values.

When executing, variables can be bound with the initBindings keyword parameter.

resource_example Module

RDFLib has a Resource class, for a resource-centric API. The Graph class also has a resource function that can be used to create resources and manipulate them by quickly adding or querying for triples where this resource is the subject.

This example shows g.resource() in action.

berkeleydb_example Module

BerkeleyDB in use as a persistent Graph store.

Example 1: simple actions

  • creating a ConjunctiveGraph using the BerkeleyDB Store

  • adding triples to it

  • counting them

  • closing the store, emptying the graph

  • re-opening the store using the same DB files

  • getting the same count of triples as before

Example 2: larger data

  • loads multiple graphs downloaded from GitHub into a BerkeleyDB-baked graph stored in the folder gsq_vocabs.

  • does not delete the DB at the end so you can see it on disk

examples.berkeleydb_example.example_1()[source]

Creates a ConjunctiveGraph and performs some BerkeleyDB tasks with it

examples.berkeleydb_example.example_2()[source]

Loads a number of SKOS vocabularies from GitHub into a BerkeleyDB-backed graph stored in the local folder ‘gsq_vocabs’

Should print out the number of triples after each load, e.g.:

177 248 289 379 421 628 764 813 965 1381 9666 9719 …

slice Module

RDFLib Graphs (and Resources) can be “sliced” with [] syntax

This is a short-hand for iterating over triples.

Combined with SPARQL paths (see foafpaths.py) - quite complex queries can be realised.

See rdflib.graph.Graph.__getitem__() for details

smushing Module

A FOAF smushing example.

Filter a graph by normalizing all foaf:Persons into URIs based on their mbox_sha1sum.

Suppose I get two FOAF documents each talking about the same person (according to mbox_sha1sum) but they each used a rdflib.term.BNode for the subject. For this demo I’ve combined those two documents into one file:

This filters a graph by changing every subject with a foaf:mbox_sha1sum into a new subject whose URI is based on the sha1sum. This new graph might be easier to do some operations on.

An advantage of this approach over other methods for collapsing BNodes is that I can incrementally process new FOAF documents as they come in without having to access my ever-growing archive. Even if another 65b983bb397fb71849da910996741752ace8369b document comes in next year, I would still give it the same stable subject URI that merges with my existing data.

sparql_query_example Module

SPARQL Query using rdflib.graph.Graph.query()

The method returns a Result, iterating over this yields ResultRow objects

The variable bindings can be accessed as attributes of the row objects For variable names that are not valid python identifiers, dict access (i.e. with row[var] / __getitem__) is also possible.

vars contains the variables

sparql_update_example Module

SPARQL Update statements can be applied with rdflib.graph.Graph.update()

sparqlstore_example Module

Simple examples showing how to use the SPARQLStore

swap_primer Module

This is a simple primer using some of the example stuff in the Primer on N3:

http://www.w3.org/2000/10/swap/Primer

transitive Module

An example illustrating how to use the transitive_subjects() and transitive_objects() graph methods

Formal definition

The transitive_objects() method finds all nodes such that there is a path from subject to one of those nodes using only the predicate property in the triples. The transitive_subjects() method is similar; it finds all nodes such that there is a path from the node to the object using only the predicate property.

Informal description, with an example

In brief, transitive_objects() walks forward in a graph using a particular property, and transitive_subjects() walks backward. A good example uses a property ex:parent, the semantics of which are biological parentage. The transitive_objects() method would get all the ancestors of a particular person (all nodes such that there is a parent path between the person and the object). The transitive_subjects() method would get all the descendants of a particular person (all nodes such that there is a parent path between the node and the person). So, say that your URI is ex:person.

This example would get all of your (known) ancestors, and then get all the (known) descendants of your maternal grandmother.

Warning

The transitive_objects() method has the start node as the first argument, but the transitive_subjects() method has the start node as the second argument.

User-defined transitive closures

The method transitiveClosure() returns transtive closures of user-defined functions.

secure_with_audit Module

This example demonstrates how to use Python audit hooks to block access to files and URLs.

It installs a audit hook with sys.addaudithook that blocks access to files and URLs that end with blocked.jsonld.

The code in the example then verifies that the audit hook is blocking access to URLs and files as expected.

examples.secure_with_audit.audit_hook(name, args)[source]

An audit hook that blocks access when an attempt is made to open a file or URL that ends with blocked.jsonld.

Details of the audit events can be seen in the audit events table.

Parameters:
  • name (str) – The name of the audit event.

  • args (Tuple[Any, ...]) – The arguments of the audit event.

Return type:

None

Returns:

None if the audit hook does not block access.

Raises:

PermissionError – If the file or URL being accessed ends with blocked.jsonld.

examples.secure_with_audit.main()[source]

The main code of the example.

The important steps are: :rtype: None

  • Install a custom audit hook that blocks some URLs and files.

  • Attempt to parse a JSON-LD document that will result in a blocked URL being accessed.

  • Verify that the audit hook blocked access to the URL.

  • Attempt to parse a JSON-LD document that will result in a blocked file being accessed.

  • Verify that the audit hook blocked access to the file.

secure_with_urlopen Module

This example demonstrates how to use a custom global URL opener installed with urllib.request.install_opener to block access to URLs.

class examples.secure_with_urlopen.SecuredHTTPHandler(debuglevel=0)[source]

Bases: HTTPHandler

A HTTP handler that blocks access to URLs that end with “blocked.jsonld”.

__module__ = 'examples.secure_with_urlopen'
http_open(req)[source]

Block access to URLs that end with “blocked.jsonld”.

Parameters:

req (Request) – The request to open.

Return type:

HTTPResponse

Returns:

The response.

Raises:

PermissionError – If the URL ends with “blocked.jsonld”.

examples.secure_with_urlopen.main()[source]

The main code of the example.

The important steps are: :rtype: None

  • Install a custom global URL opener that blocks some URLs.

  • Attempt to parse a JSON-LD document that will result in a blocked URL being accessed.

  • Verify that the URL opener blocked access to the URL.