【问题标题】:Run Cx_Oracle query in Flask App在 Flask App 中运行 Cx_Oracle 查询
【发布时间】:2015-10-27 19:19:15
【问题描述】:

我正在尝试构建一个应用程序,该应用程序具有一个页面,我在其中输入一个 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 是否按预期获取参数
  • 可能是因为 show_entries 需要 url_for(show_entries) 中的 account_id
  • 针对错误进行了编辑。表单操作实际上路由到“entry”方法,该方法应该重定向到“show_entries”并提供变量。
  • 在入口路径中修改return redirect(url_for('show_entries', account_id=account_id))是否有效?

标签: python sql oracle flask cx-oracle


【解决方案1】:

您收到该错误是因为您的 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。

【讨论】:

  • 好的,改变它,实际上只是从方法中删除了 arg。现在我运行类似于你的建议,但我得到一个 TypeError: Expecting a dictionary, sequence or keyword args
  • 你能确定错误发生在哪一行吗?
  • 原来这是一个 Oracle DB 的东西。我添加了 c.execute(sql, account_id=account_id) 并且效果很好。感谢您的帮助。
【解决方案2】:

使这项工作的补充在这里。我原始代码中的其他所有内容都很好,即使不是最佳的。

        c.execute(sql, account_id=account_id)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-11-11
    • 2021-06-24
    • 2021-11-11
    • 2020-07-09
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多