使用restapi向mysql传递三个参数

vc9ivgsu  于 2021-06-21  发布在  Mysql
关注(0)|答案(1)|浏览(347)

我需要在flask中使用python构建一个路由,允许通过uri传递3个参数,这样我就可以在mysql查询中使用这3个参数。
数据库表的3列中各有3个参数,最终结果查询类似于:

  1. Select * from maintable where (field1= param1 and field2 = param2 and field3 = param3);

我希望uri看起来像:http://my.api.com/search/123/345/dd5432
python代码如下所示

  1. @app.route('/search/param1/param2/param3')
  2. def get():
  3. cur = mysql.connect().cursor()
  4. cur.execute('''select * from maindb.maintable''')
  5. r = [dict((cur.description[i][0], value)
  6. for i, value in enumerate(row)) for row in cur.fetchall()]
  7. return jsonify({'results' : r})

到目前为止,我已经能够成功地传递1个参数,并使用它来查询数据库中的1列。

piwo6bdm

piwo6bdm1#

首先,您需要更改路由规则,以便能够提取其中的一部分。然后需要在sql查询中发送这些参数。但是,不要直接从用户输入构建sql查询,因为它可能会引入sql注入漏洞。使用占位符,然后将参数作为元组提交给db游标 execute() :

  1. @app.route('/search/<param1>/<param2>/<param3>')
  2. def get(param1, param2, param3):
  3. cur = mysql.connect().cursor()
  4. cur.execute('''select * from maindb.maintable where field1 = %s and field2 = %s and field3 = %s''',
  5. (param1, param2, param3))
  6. r = [dict((cur.description[i][0], value)
  7. for i, value in enumerate(row)) for row in cur.fetchall()]
  8. return jsonify({'results': r})

相关问题