使用用户输入创建python sparql查询

问题描述

我正在尝试使用python构建sparql查询并从用户那里获取一些数据

这是我的代码

@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

我收到以下错误

enter image description here

查询的工作方式如下:

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")}
    """))

但是问题是我想从api方法获取用户输入

解决方法

这是在查询中使用%s的方法

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))