【问题标题】:Flask getting variable from url not workingFlask从url获取变量不起作用
【发布时间】:2022-07-07 22:26:29
【问题描述】:

我确定我缺少一些简单的东西,但我无法看到它。

这里是将数据发送到 url 的按钮

<p class='text-right'><a href='{{url_for('add_comment', id=datas[0] )}}' class='btn btn-success '>Add Comment</a></p>

我通过 url 将一个 id 从一个烧瓶模板传递到另一个模板

http://localhost:5000/add_comment?id=8

那么这里是处理它的代码

@app.route('/add_comment', methods=['GET', 'POST'])
def add_comment():
    _ip = request.remote_addr
    _id = request.args['id']
    print (_id)
    print ("---------")
    if request.method=='POST':
        _id = _id
        comment= request.form['comment']
        commentuname = request.form['commentuname']
        createDate = today.strftime("%m/%d/%y")
        conn = connection()
        cur = conn.cursor()
        cur.execute("insert into dtable (reqID, comment, commentuname, createDate, ipaddress) values(?,?,?,?,?)", (_id, comment, commentuname, createDate, _ip))
    return redirect(url_for('index'))
return render_template("add_comment.html")

我的打印语句打印出正确的值,

8
----------

但是页面出错了

werkzeug.exceptions.BadRequestKeyError: 400 Bad Request: 
The browser (or proxy) sent a request that this server could not 
understand.KeyError: 'id'

任何人都可以看到我缺少的会导致此错误的东西吗?我知道什么是关键错误,但不知道如何解决它

编辑: 当我使用 get 时,我没有收到 id 值,并且收到以下错误

_id = request.args.get('id')

127.0.0.1 - - [07/Jul/2022 09:12:13] "GET /add_comment?id=8 HTTP/1.1" 
200 -
None
---------

pyodbc.IntegrityError: ('23000', "[23000] [Microsoft][ODBC Driver 17 for 
SQL Server][SQL Server]Cannot insert the value NULL into column 'reqID', 
table 'DB.dbo.dtable'; column does not allow nulls. INSERT fails. (515) 
(SQLExecDirectW); [23000] [Microsoft][ODBC Driver 17 for SQL Server][SQL 
Server]The statement has been terminated. (3621)")

【问题讨论】:

  • 当您在没有id 参数的浏览器中打开http://localhost:5000/add_comment 时可能会引发异常,这会导致KeyError on request.args['id']
  • 嗯,不知道,那会不会只适用于get而不是post,当我发帖时,它应该重定向到索引
  • 试试 _id = request.args.get('id')
  • 我在我的回答中给了你一个最小的例子,它适用于获取和发布。我建议您重新检查您的代码以找出您的代码不起作用的原因。
  • 另外 _id = _id 的目的是什么?

标签: python flask jinja2


【解决方案1】:

您假设总是有一个 'id' 的值,除非没有,请改用 get 方法。

文档建议使用 get 或通过捕获 KeyError 来访问 URL 参数,因为用户可能会更改 URL 并向他们显示 400 bad request 页面,在这种情况下对用户不友好。

@app.route('/add_comment', methods=['GET', 'POST'])
def add_comment():
    _ip = request.remote_addr
    _id = request.args.get('id') # This line is only change
    print (_id)
    print ("---------")
    if request.method=='POST':
        _id = _id
        comment= request.form['comment']
        commentuname = request.form['commentuname']
        createDate = today.strftime("%m/%d/%y")
        conn = connection()
        cur = conn.cursor()
        cur.execute("insert into dtable (reqID, comment, commentuname, createDate, ipaddress) values(?,?,?,?,?)", (_id, comment, commentuname, createDate, _ip))
    return redirect(url_for('index'))
return render_template("add_comment.html")

最小可复制示例:

from flask import Flask, request

app = Flask(__name__)

@app.route('/', methods=['GET', 'POST'])
def add_comment():
    _id = request.args.get('id') # This line is only change
    print (_id)
    print ("---------")
    if request.method=='POST':
        _id = _id
        print(_id)
        comment= request.form['comment']
        print(comment)
        return 'in post'
    return 'in get'


if __name__ == '__main__':
    app.run(debug=True)

# curl -d "comment=mycomment" -X POST http://localhost:5000?id=hello

# hello
# mycomment
# 127.0.0.1 - - [07/Jul/2022 15:20:11] "POST /?id=hello HTTP/1.1" 200 -

【讨论】:

  • “id”在 URL 中?
  • 我刚刚在本地测试过,效果很好。 _id = request.args.get('id') 就是你所需要的。
猜你喜欢
  • 1970-01-01
  • 2016-05-13
  • 2014-03-14
  • 2018-06-14
  • 2011-09-28
  • 2014-12-04
相关资源
最近更新 更多