Skip to content

Commit

Permalink
Merge pull request #26 from eea/develop
Browse files Browse the repository at this point in the history
Develop #111217
  • Loading branch information
Petchesi-Iulian authored Jun 17, 2020
2 parents e4300f3 + 48de449 commit 9ace689
Show file tree
Hide file tree
Showing 4 changed files with 128 additions and 6 deletions.
125 changes: 121 additions & 4 deletions README.rst
Original file line number Diff line number Diff line change
Expand Up @@ -11,12 +11,12 @@ SPARQL HTTP client library
:target: https://eggrepo.eea.europa.eu/d/sparql-client/
:alt: Release

`sparql-client` is a library to query a SPARQL endpoint. It will automatically
convert literals to the coresponding Python types.
`sparql-client` is a SPARQL query library that performs SELECT and ASK queries against a SPARQL endpoint via HTTP.
It will automatically convert literals to the coresponding Python types.

Visit http://www.eionet.europa.eu/software/sparql-client/ for documentation and
examples.
API based on SPARQL_JavaScript_Library_ by Lee Feigenbaum and Elias Torres. Heavy influence from Juan Manuel Caicedo’s SPARQL library.

.. _SPARQL_JavaScript_Library: https://web.archive.org/web/20120518014957/http://www.thefigtrees.net/lee/sw/sparql.js

API
---
Expand All @@ -38,6 +38,115 @@ If you have made an ASK query, then you can read the result (a boolean value) wi
works = result.hasresult()


How it works
------------

>>> import sparql

>>> q = ('SELECT DISTINCT ?station, ?orbits WHERE { '
... '?station a <http://dbpedia.org/ontology/SpaceStation> . '
... '?station <http://dbpedia.org/property/orbits> ?orbits . '
... 'FILTER(?orbits > 50000) } ORDER BY DESC(?orbits)')
>>> result = sparql.query('http://dbpedia.org/sparql', q)

>>> result.variables
[u'station', u'orbits']

>>> for row in result:
... print 'row:', row
... values = sparql.unpack_row(row)
... print values[0], "-", values[1], "orbits"
row: (<IRI <http://dbpedia.org/resource/Mir>>, <Literal "86331"^^<http://www.w3.org/2001/XMLSchema#int>>)
http://dbpedia.org/resource/Mir - 86331 orbits
row: (<IRI <http://dbpedia.org/resource/Salyut_7>>, <Literal "51917"^^<http://www.w3.org/2001/XMLSchema#int>>)
http://dbpedia.org/resource/Salyut_7 - 51917 orbits

sparql module
-------------

The ``sparql`` module can be invoked in several different ways. To quickly run a query use ``query()``. Results are encapsulated in a ``_ResultsParser`` instance:

>>> result = sparql.query(endpoint, query)
>>> for row in result:
>>> print row

Command-line use
================

>>> sparql.py [-i] endpoint
-i Interactive mode

If interactive mode is enabled, the program reads queries from the console and then executes them. Use a double line (two ‘enters’) to separate queries.
Otherwise, the query is read from standard input.

RDF wrapper classes
===================

class sparql.RDFTerm
Super class containing methods to override. ``sparql.IRI``, ``sparql.Literal`` and ``sparql.BlankNode`` all inherit from ``sparql.RDFTerm``.

``n3()``

Return a Notation3 representation of this term.

``class sparql.IRI(value)``

An RDF resource.

``class sparql.Literal(value, datatype=None, lang=None)``

Literals. These can take a data type or a language code.

``class sparql.BlankNode(value)``

Blank node. Similar to IRI but lacks a stable identifier.

Query utilities

``class sparql.Service(endpoint, qs_encoding='utf-8')``

This is the main entry to the library. The user creates a Service, then sends a query to it. If we want to have persistent connections, then open them here.

``class sparql._ResultsParser(fp)``

Parse the XML result.

``__iter__()``

Synonim for fetchone().

``fetchall()``

Loop through the result to build up a list of all rows. Patterned after DB-API 2.0.

``fetchone()``

Fetches the next set of rows of a query result, returning a list. An empty list is returned when no more rows are available. If the query was an ASK request, then an empty list is returned as there are no rows available.

``hasresult()``

ASK queries are used to test if a query would have a result. If the query is an ASK query there won’t be an actual result, and fetchone() will return nothing. Instead, this method can be called to check the result from the ASK query.

If the query is a SELECT statement, then the return value of hasresult() is None, as the XML result format doesn’t tell you if there are any rows in the result until you have read the first one.

``sparql.parse_n3_term(src)``

Parse a Notation3 value into a RDFTerm object (IRI or Literal).

This parser understands IRIs and quoted strings; basic non-string types (integers, decimals, booleans, etc) are not supported yet.

``sparql.unpack_row(row, convert=None, convert_type={})``

Convert values in the given row from RDFTerm objects to plain Python values: IRI is converted to a unicode string containing the IRI value; BlankNode is converted to a unicode string with the BNode’s identifier, and Literal is converted based on its XSD datatype.

The library knows about common XSD types (STRING becomes unicode, INTEGER and LONG become int, DOUBLE and FLOAT become float, DECIMAL becomes Decimal, BOOLEAN becomes bool). If the python-dateutil library is found, then DATE, TIME and DATETIME are converted to date, time and datetime respectively. For other conversions, an extra argument convert may be passed. It should be a callable accepting two arguments: the serialized value as a unicode object, and the XSD datatype.

``sparql.query(endpoint, query)``

Convenient method to execute a query. Exactly equivalent to:

``sparql.Service(endpoint).query(query)``

Conversion of data types
------------------------

Expand All @@ -59,6 +168,14 @@ Tested under Python 2.4 through 2.7.
.. _python-dateutil: http://niemeyer.net/python-dateutil
.. _mock: http://www.voidspace.org.uk/python/mock/

Installing sparql-client
------------------------

The ``sparql-client`` library is available from PyPI and has no dependencies. Installation is as simple as:

pip install sparql-client

We recommend also instlaling ``python-dateutil``, to enable parsing of dates and times from query results

License
-------
Expand Down
5 changes: 5 additions & 0 deletions docs/HISTORY.txt
Original file line number Diff line number Diff line change
@@ -1,6 +1,11 @@
Changelog
=========

3.7 - (2020-06-17)
---------------------------
* Feature: added the documentation originally found under eionet.euripa.eu
[alecghica refs #111217]

3.6 - (2020-03-03)
---------------------------
* Change: Add jenkins badge
Expand Down
2 changes: 1 addition & 1 deletion sparql.py
Original file line number Diff line number Diff line change
Expand Up @@ -632,7 +632,7 @@ def hasresult(self):
return self._hasResult

def __iter__(self):
""" Synonim for :func:`fetchone`. """
""" Synonym for :func:`fetchone`. """
return self.fetchone()

def fetchone(self):
Expand Down
2 changes: 1 addition & 1 deletion version.txt
Original file line number Diff line number Diff line change
@@ -1 +1 @@
3.6
3.7

0 comments on commit 9ace689

Please sign in to comment.