我需要使用 python 在 flask 中构建一个路由,允许通过 URI 传递 3 个参数,这样我就可以在 MySQL 查询中使用这 3 个参数。
数据库表在 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能够提取它的一部分。然后您需要在 SQL 查询中发送这些参数。但是,不要直接从用户输入构建 SQL 查询,因为它可能会引入 SQL 注入(inject)漏洞。使用 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 REST API 将三个参数传递给 MySQL,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52351833/