使用 Flask REST API 将三个参数传递给 MySQL
Pass three parameters to MySQL using Flask REST API
我需要使用 python 在 flask 中构建一个路由,允许通过 URI 传递 3 个参数,这样我就可以在 MySQL 查询中使用这 3 个参数。
数据库 table 在 3 列中有 3 个参数中的每一个,最终结果查询类似于:
Select * from maintable where (field1= param1 and field2 = param2 and field3 = param3);
我希望 URI 看起来像:http://my.api.com/search/123/345/DD5432
python 代码如下所示
@app.route('/search/param1/param2/param3')
def get():
cur = mysql.connect().cursor()
cur.execute('''select * from maindb.maintable''')
r = [dict((cur.description[i][0], value)
for i, value in enumerate(row)) for row in cur.fetchall()]
return jsonify({'results' : r})
到目前为止,我已经能够成功传递 1 个参数并使用它来查询我数据库中的 1 列。
首先您需要更改 route rule to be able to extract parts of it. And then you need to send these parameters within the SQL query. However, don't build your SQL query from the user input directly since it could introduce an SQL injection vulnerability. Use placeholders 然后将您的参数作为元组提交给数据库游标 execute()
:
@app.route('/search/<param1>/<param2>/<param3>')
def get(param1, param2, param3):
cur = mysql.connect().cursor()
cur.execute('''select * from maindb.maintable where field1 = %s and field2 = %s and field3 = %s''',
(param1, param2, param3))
r = [dict((cur.description[i][0], value)
for i, value in enumerate(row)) for row in cur.fetchall()]
return jsonify({'results': r})
我需要使用 python 在 flask 中构建一个路由,允许通过 URI 传递 3 个参数,这样我就可以在 MySQL 查询中使用这 3 个参数。
数据库 table 在 3 列中有 3 个参数中的每一个,最终结果查询类似于:
Select * from maintable where (field1= param1 and field2 = param2 and field3 = param3);
我希望 URI 看起来像:http://my.api.com/search/123/345/DD5432
python 代码如下所示
@app.route('/search/param1/param2/param3')
def get():
cur = mysql.connect().cursor()
cur.execute('''select * from maindb.maintable''')
r = [dict((cur.description[i][0], value)
for i, value in enumerate(row)) for row in cur.fetchall()]
return jsonify({'results' : r})
到目前为止,我已经能够成功传递 1 个参数并使用它来查询我数据库中的 1 列。
首先您需要更改 route rule to be able to extract parts of it. And then you need to send these parameters within the SQL query. However, don't build your SQL query from the user input directly since it could introduce an SQL injection vulnerability. Use placeholders 然后将您的参数作为元组提交给数据库游标 execute()
:
@app.route('/search/<param1>/<param2>/<param3>')
def get(param1, param2, param3):
cur = mysql.connect().cursor()
cur.execute('''select * from maindb.maintable where field1 = %s and field2 = %s and field3 = %s''',
(param1, param2, param3))
r = [dict((cur.description[i][0], value)
for i, value in enumerate(row)) for row in cur.fetchall()]
return jsonify({'results': r})