python - 使用 Flask REST API 将三个参数传递给 MySQL

标签 python mysql flask-restful

我需要使用 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/

相关文章:

python - 删除括号内包含的文本

python - 如何将 zip 文件的子集导入到 colab 中?

mysql - 无法连接到 Web 托管的 MySQL 数据库

sql - 无法删除或更新父行 - 使用 Hibernate 的 JPA

python - 如何将 url_map.iter_rules 与蓝图对象而不是应用程序一起使用

python - 类型错误 : <Response 36 bytes [200 OK]> is not JSON serializable

python - 将 Pandas 中的昵称与名字相匹配

Python 进程不会在 GTK 循环退出时退出

html - 删除隐藏元素和表单提交之间的空间

python - 类型错误 : wrapper() got an unexpected keyword argument 'nam' while using @jwt_required