运行 Cx_Oracle 在 Flask App 中查询

Run Cx_Oracle query in Flask App

我正在尝试构建一个应用程序,该应用程序有一个页面,我在该页面上输入了一个 ID,然后 运行 对其进行查询并显示结果。我目前的代码如下。

我保留了一个 werkzeug 错误:

BuildError: ('show_entries', {}, None)

app.py

import cx_Oracle

# Run the query to display the results
@app.route('/matcher/<int:account_id>', methods=['GET', 'POST'])
def show_entries(account_id):
    sql = """SELECT item1, 
             item2, 
             item3, 
             item4, 
             item5, 
             item6
             FROM TABLE
             WHERE account_id = ?"""
    c = g.db.cursor()
    c.execute(sql, account_id)

您收到该错误是因为您的 show_entries 方法需要一个 account_id 参数,但您的 url_for 调用没有提供一个参数。

您似乎在尝试让 show_entries 方法将 account_id 参数作为表单中的 GET 值,但作为 URL 的一部分(不是GET 参数)在方法定义中,所以你有一个不匹配。

您可以在方法定义中给 account_id 变量一个默认值,并检查它是否存在于 GET 参数中:

@app.route('/matcher/', methods=['GET', 'POST'])
@app.route('/matcher/<int:account_id>', methods=['GET', 'POST'])
def show_entries(account_id=0):
    if request.method == 'GET' and not account_id:
        account_id = request.args.get('account_id', 0)
    ...

文档:url_for, request.args.get.

使这项工作成功的补充就在这里。我原始代码中的其他一切都很好,即使不是最佳的。

        c.execute(sql, account_id=account_id)