【问题标题】:How to pass id from flask app to mysql database如何将 id 从烧瓶应用程序传递到 mysql 数据库
【发布时间】:2017-10-24 12:10:31
【问题描述】:

我有一个连接到 MySQL 数据库的烧瓶应用程序。

注意

数据库名称 = 评估

表名 = 评估

列 = eval_id、eval_name、日期

我有一个“评估表”,其中包含字段 eval_id、eval_name 和日期。

 mysql> use evaluation;
    mysql> describe evaluation;
    +-----------+-------------+------+-----+---------+-------+
    | Field     | Type        | Null | Key | Default | Extra |
    +-----------+-------------+------+-----+---------+-------+
    | eval_id   | int(11)     | NO   | PRI | NULL    |       |
    | eval_name | varchar(20) | NO   |     | NULL    |       |
    | date      | datetime(6) | NO   |     | NULL    |       |
    +-----------+-------------+------+-----+---------+-------+

如何编写 API 以通过其 id 获取特定评估? 我尝试了以下方法,但它不起作用。

@app.route('/getEval/<int:eval_id>', methods=['GET'])
def getEvalByID(eval_id):
    cur.execute('''select * from evaluation.evaluation where eval_id=eval_id''')
    res = cur.fetchall()
    return jsonify({'test':str(res)})

我怎样才能更正这个问题并仅根据 app.route 中提到的 eval_id 获得评估。

【问题讨论】:

    标签: python flask get flask-restful


    【解决方案1】:

    您需要将 eval_id 不是 String 而是 VAR。

    @app.route('/getEval/<int:eval_id>', methods=['GET'])
    def getEvalByID(eval_id):
        cur.execute('select * from evaluation.evaluation where eval_id=' + str(eval_id))
        res = cur.fetchall()
        return jsonify({'test':str(res)})
    

    【讨论】:

    • 感谢您的回答。但我收到以下错误cur.execute('select * from evaluation.evaluation where eval_id=' + eval_id, '') TypeError: cannot concatenate 'str' and 'int' objects
    • 已修复。立即尝试
    • 现在我得到query = query % self._escape_args(args, conn) TypeError: not all arguments converted during string formatting
    • cur.execute 行中字符串的创建是混合的。它不传递单个字符串作为参数。试试这个:'select * from evaluation.evaluation where eval_id=' + str(eval_id)
    • 如果 args 为空,我们可以摆脱它们,再次尝试使用固定的单个参数:O
    【解决方案2】:

    尝试使用 cur.execute('select * from evaluation.evaluation where eval_id={}'.format(eval_id))

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-04-05
      • 2019-07-19
      • 2021-12-23
      • 2020-12-21
      • 2022-12-01
      • 2020-09-26
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多