Python 生成select查询以扫描用户指定的列

Python 生成select查询以扫描用户指定的列,python,flask,sqlalchemy,flask-sqlalchemy,Python,Flask,Sqlalchemy,Flask Sqlalchemy,我试图创建一个API,允许用户通过将列名作为参数传递,根据他们希望使用的任何列来查询数据库 @app.route('/api/restaurants/search1/',methods=['GET']) def search(): col = request.args['col'] key = request.args['key'] restaurant = Restaurant.query.filter(Restaurant.menu_type.like("%"+key

我试图创建一个API,允许用户通过将列名作为参数传递,根据他们希望使用的任何列来查询数据库

@app.route('/api/restaurants/search1/',methods=['GET'])
def search():
    col = request.args['col']
    key = request.args['key']
    restaurant = Restaurant.query.filter(Restaurant.menu_type.like("%"+key+"%")).all()
    return jsonify(json_list=[i.serialize for i in restaurant])
我试图用用户为变量“col”输入的任何内容来替换当前列的“Menu\u type”。如有任何帮助,将不胜感激。

您只需使用函数即可。若要避免对象已请求属性但它不是表列(例如方法)的情况,请选中
Restaurant.\uuuu table\uuuu.c
-表列集合:

@app.route('/api/restaurants/search1/',methods=['GET'])
def search():
    col = request.args['col']
    key = request.args['key']
    if col in Restaurant.__table__.c:
        restaurant = Restaurant.query.filter(getattr(Restaurant, col).like("%"+key+"%")).all()
    else:
        raise RuntimeError('Restaurant table doesn`t have column %s' % col)
    return jsonify(json_list=[i.serialize for i in restaurant])
您可以只使用函数。若要避免对象已请求属性但它不是表列(例如方法)的情况,请选中
Restaurant.\uuuu table\uuuu.c
-表列集合:

@app.route('/api/restaurants/search1/',methods=['GET'])
def search():
    col = request.args['col']
    key = request.args['key']
    if col in Restaurant.__table__.c:
        restaurant = Restaurant.query.filter(getattr(Restaurant, col).like("%"+key+"%")).all()
    else:
        raise RuntimeError('Restaurant table doesn`t have column %s' % col)
    return jsonify(json_list=[i.serialize for i in restaurant])