examples Package — rdflib 7.1.4 documentation (original) (raw)
These examples all live in ./examples
in the source-distribution of RDFLib.
datasets Module¶
This module contains a number of common tasks using the RDFLib Dataset class.
An RDFLib Dataset is an object that stores multiple Named Graphs - instances of RDFLib Graph identified by IRI - within it and allows whole-of-dataset or single Graph use.
Dataset extends Graph’s Subject, Predicate, Object structure to include Graph - archaically called Context - producing quads of s, p, o, g.
There is an older implementation of a Dataset-like class in RDFLib < 7.x called ConjunctiveGraph that is now deprecated.
Sections in this module:
- Creating & Growing Datasets
- Looping & Counting triples/quads in Datasets
- Manipulating Graphs with Datasets
jsonld_serialization Module¶
JSON-LD is “A JSON-based Serialization for Linked Data” (https://www.w3.org/TR/json-ld/) that RDFLib implements for RDF serialization.
This file demonstrated some of the JSON-LD things you can do with RDFLib. Parsing & serializing so far. More to be added later.
Parsing¶
There are a number of “flavours” of JSON-LD - compact and verbose etc. RDFLib can parse all of these in a normal RDFLib way.
Serialization¶
JSON-LD has a number of options for serialization - more than other RDF formats. For example, IRIs within JSON-LD can be compacted down to CURIES when a “context” statement is added to the JSON-LD data that maps identifiers - short codes - to IRIs and namespace IRIs like this:
"@context": { "dcterms": "http://purl.org/dc/terms/", "schema": "https://schema.org/" }
Here the short code “dcterms” is mapped to the IRI http://purl.org/dc/terms/ and “schema” to https://schema.org/, as per RDFLib’s in-build namespace prefixes.
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 theinitBindings
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 afoaf:mbox_sha1sum
into a new subject whose URI is based on thesha1sum
. 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 another65b983bb397fb71849da910996741752ace8369b
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 thetransitive_subjects() andtransitive_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. Thetransitive_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, andtransitive_subjects() walks backward. A good example uses a property ex:parent
, the semantics of which are biological parentage. Thetransitive_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). Thetransitive_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 isex:person
.
This example would get all of your (known) ancestors, and then get all the (known) descendants of your maternal grandmother.
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:
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'¶
Block access to URLs that end with “blocked.jsonld”.
Parameters:
req (Request) – The request to open.
Return type:
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.