简体   繁体   中英

python sparql query creating with user input

I am trying to build sparql query using python and take some data from user

this is my code :

@app.route('/api/v1/getCourseByCode', methods=['GET'])
def api_getCourseByCode():
    if 'courseId' in request.args:
        courseId = request.args['courseId']
    else:
        return "Error: No course id provided. Please specify an course id."

    onto = get_ontology("https://website/lumiere8.owl")
    onto.load()
    graph = onto.world.as_rdflib_graph()

    query = """PREFIX lumiere: <http://www.smacrs.com/lumiere.owl#>
            SELECT ?individual
            WHERE { ?individual a lumiere:Course ;
                    lumiere:Code ?propertyValue .
            FILTER(STR(?propertyValue) = {fname})}""".format(fname=courseId)

    print("---------------------------------------")
    print(query)

    course = list(graph.query_owlready(query))
    print(course)
    return course

and I got the following error :

在此处输入图片说明

The query is working like this :

course = list(graph.query_owlready("""PREFIX lumiere: <http://www.smacrs.com/lumiere.owl#>
    SELECT ?individual
    WHERE { ?individual a lumiere:Course ;
                    lumiere:Code ?propertyValue .
    FILTER(STR(?propertyValue) = "CS101")}
    """))

but the problem is that I want to take user input from the api method

This is what works with me using %s in the query

course=list(graph.query_owlready("""PREFIX lumiere: <http://www.smacrs.com/lumiere.owl#>
    SELECT ?individual
    WHERE { ?individual a lumiere:Course ;
                    lumiere:Code ?propertyValue .
    FILTER(STR(?propertyValue) = "%s")}
    """ %courseId))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM