Skip to content
Snippets Groups Projects

- sparql_view implementation

Closed Quentin Ulmer requested to merge 4/backend-skeleton into Dev
@@ -5,46 +5,38 @@ from SPARQLWrapper import SPARQLWrapper, JSON
@@ -5,46 +5,38 @@ from SPARQLWrapper import SPARQLWrapper, JSON
import os
import os
import json
import json
def sparql_query(request):
def sparql_query(request):
"""
"""
This function executes a SPARQL query and returns the results in JSON format.
This function executes a SPARQL query received from the frontend and returns the results in JSON format.
The SPARQL endpoint is read from the environment variables. (set in Docker-compose)
The SPARQL endpoint is read from the environment variables. (set in Docker-compose)
"""
"""
sparql_endpoint = 'http://fuseki:3030/data/query'
sparql_endpoint = 'http://fuseki:3030/data/query'
sparql = SPARQLWrapper(sparql_endpoint)
sparql = SPARQLWrapper(sparql_endpoint)
sparql.setReturnFormat(JSON)
sparql.setReturnFormat(JSON)
sparql.setQuery("""
try:
PREFIX : <http://h-da.de/fbi/art/>
# Extract SPARQL query from POST request
PREFIX rdf: <http://www.w3.org/1999/02/22-rdf-syntax-ns#>
body = json.loads(request.body)
PREFIX rdfs: <http://www.w3.org/2000/01/rdf-schema#>
sparql_query = body.get('query', '')
PREFIX wd: <http://www.wikidata.org/entity/>
if not sparql_query:
SELECT ?g ?db ?dd ?pb ?pd
return JsonResponse({"error": "No query provided"}, status=400)
WHERE {
?p a :person ;
sparql.setQuery(sparql_query)
rdfs:label "Michelangelo";
:gender ?g;
response = sparql.query().convert()
:date_of_birth ?db;
:date_of_death ?dd ;
# Log the raw response for debugging
:place_of_death ?pd .
if isinstance(response, bytes):
}
raw_response = response.decode('utf-8')
""")
else:
raw_response = response
try:
print("Raw response:", raw_response) # Debugging output
response = sparql.query().convert()
# Log the raw response for debugging
# Ensure the response is properly decoded
if isinstance(response, bytes):
if isinstance(response, bytes):
raw_response = response.decode('utf-8')
response = json.loads(response.decode('utf-8'))
else:
results = response.get("results", {}).get("bindings", [])
raw_response = response
return JsonResponse(results, safe=False)
print("Raw response:", raw_response) # Debugging output
except Exception as e:
return JsonResponse({"error": str(e)}, status=500)
# Ensure the response is properly decoded
if isinstance(response, bytes):
response = json.loads(response.decode('utf-8'))
results = response.get("results", {}).get("bindings", [])
return JsonResponse(results, safe=False)
except Exception as e:
return JsonResponse({"error": str(e)}, status=500)
Loading