gpt4 book ai didi

python - flask (Python): Pass input as parameter to function of different route with fixed URL

转载 作者:行者123 更新时间:2023-12-03 23:37:42 25 4
gpt4 key购买 nike

如何让表单上提交的用户输入显示在固定 URL 上?

@app.route('/', methods=['GET','POST'])
def main():
if request.method == 'POST':
msg = request.form['message']
return redirect(url_for('display_msg', msg=msg))
else:
return form


@app.route('/msg')
def display_msg(msg):
return msg

提交表单时出现以下错误:

TypeError: display_msg() 缺少 1 个必需的位置参数:'msg'

如果我初始化 msg,这段代码实际上可以正常工作作为全局变量,然后执行 global msgmain 的顶部,但它不允许我通过 msg作为 display_msg 的参数.

另一种可行的方法是,如果我更改 @app.route('/msg')@app.route('/<string:msg>') ,但这会将 URL 更改为用户在表单上提交的任何内容,这不是我想要的。我想修复 URL。

最佳答案

由于来自msg 的数据已经存储在请求对象中,而不是将其作为参数传递给display_msg,因此可以如下访问:

@app.route('/msg')
def display_msg():
return request.args.get('msg')

发生类型错误是因为 url_for 的关键字参数被传递给请求对象,而不是作为 display_msg 的参数。

关于python - flask (Python): Pass input as parameter to function of different route with fixed URL,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46741744/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com