[sparql] Enable user to set a custom useragent
authorSimon Chabot <simon.chabot@logilab.fr>
Fri, 06 Sep 2019 08:44:54 +0200
changeset 558 f462d14f893e
parent 557 7d46626336f0
child 559 45a462873223
[sparql] Enable user to set a custom useragent
nazca/utils/dataio.py
--- a/nazca/utils/dataio.py	Fri Jun 07 15:21:12 2019 +0200
+++ b/nazca/utils/dataio.py	Fri Sep 06 08:44:54 2019 +0200
@@ -105,13 +105,16 @@
 ###############################################################################
 # SPARQL FUNCTIONS ############################################################
 ###############################################################################
-def _sparqlexecute(endpoint, query, raise_on_error=False):
+def _sparqlexecute(endpoint, query, raise_on_error=False, agent=None):
     """ Execute a sparql query and return the raw results
     """
     if not SPARQL_ENABLED:
         raise ImportError("You have to install SPARQLWrapper and JSON modules to"
                           "used this function")
-    sparql = SPARQLWrapper(endpoint)
+    if agent:
+        sparql = SPARQLWrapper(endpoint, agent=agent)
+    else:
+        sparql = SPARQLWrapper(endpoint)
     sparql.setQuery(query)
     sparql.setReturnFormat(JSON)
     try:
@@ -131,11 +134,11 @@
 
 
 def sparqlquery(endpoint, query, indexes=None,
-                autocast_data=True, raise_on_error=False):
+                autocast_data=True, raise_on_error=False, agent=None):
     """ Run the sparql query on the given endpoint, and wrap the items in the
     indexes form. If indexes is empty, keep raw output"""
     results = []
-    rawresults = _sparqlexecute(endpoint, query, raise_on_error)
+    rawresults = _sparqlexecute(endpoint, query, raise_on_error, agent)
     if not rawresults:
         return results
     labels = rawresults['head']['vars']
@@ -159,12 +162,12 @@
     return results
 
 
-def sparqljson(endpoint, query, lang_order=('fr', 'en'), raise_on_error=False):
+def sparqljson(endpoint, query, lang_order=('fr', 'en'), raise_on_error=False, agent=None):
     """ Execute and format the results of a sparql query.
     Sort the litterals using lang_order.
     """
     data = {}
-    rawresults = _sparqlexecute(endpoint, query, raise_on_error)
+    rawresults = _sparqlexecute(endpoint, query, raise_on_error, agent)
     if not rawresults:
         return data
     results = rawresults["results"]["bindings"]