Very simple question about inserting a varaible in a SPARQL query in the Wrapper library. Example below in a Jupyter notebook, I defined a variable 'q'
outside SPARQL query, and would like to use it within a SPARQL query. I could not find out how to escape triple-quotation ("""
). Quick help would be appreciated. Many thanks!
!pip install SPARQLWrapper
from SPARQLWrapper import SPARQLWrapper, JSON, XML
q = '<http://data.europeana.eu/item/08517/3395FCFC5812F76279634269BE601072BF09183B>'
query_content = """
select *
where {
?providerProxy ore:proxyFor 'q' ; ?p ?o
}
"""
query = prefix + query_content
sparql.setQuery(query)
sparql.setReturnFormat(JSON)
results = sparql.query().convert()
print(results)
print('------')
for result in results["results"]["bindings"]:
p = result["p"]["value"]
o = result["o"]["value"]
print(p + " : " + o)
Somehow the following method (.format) does not work.
query_content = """
select ?providerProxy
where {
?providerProxy ore:proxyFor {var}
}
LIMIT 100
""".format(var = '<http://data.europeana.eu/item/08517/3395FCFC5812F76279634269BE601072BF09183B>')
query = prefix + query_content
sparql.setQuery(query)
sparql.setReturnFormat(JSON)
Error looks like:
HTTPError Traceback (most recent call last)
/usr/local/lib/python3.7/dist-packages/SPARQLWrapper/Wrapper.py in _query(self)
925 else:
--> 926 response = urlopener(request)
927 return response, self.returnFormat
HTTPError: HTTP Error 400: Bad Request
During handling of the above exception, another exception occurred:
QueryBadFormed Traceback (most recent call last)
/usr/local/lib/python3.7/dist-packages/SPARQLWrapper/Wrapper.py in _query(self)
928 except urllib.error.HTTPError as e:
929 if e.code == 400:
--> 930 raise QueryBadFormed(e.read())
931 elif e.code == 404:
932 raise EndPointNotFound(e.read())
QueryBadFormed: QueryBadFormed: A bad request has been sent to the endpoint: probably the SPARQL query is badly formed.
results = sparql.query().convert()
print(results)
print('------')
Similarly, f""" {} """ method does not work:
var = '<http://data.europeana.eu/item/08517/3395FCFC5812F76279634269BE601072BF09183B>'
query_content = f"""
select ?providerProxy
where {
?providerProxy ore:proxyFor {var}
LIMIT 100
"""
returns error:
File "<fstring>", line 2
?providerProxy ore)
^
SyntaxError: invalid syntax
query_content = f""" select ?providerProxy where {{ ?providerProxy ore:proxyFor {var} }} """