简体   繁体   English

在烧瓶中使用带有参数的url_for函数时重定向循环

[英]Redirect loop while using url_for function with parameters in flask

I get a redirect loop when I try to use the redirect and url_for functions in flask as follows: 当我尝试使用flask中的redirect和url_for函数时,出现如下所示的重定向循环:

@app.route('/edit/<id>' , methods=['POST', 'GET'])
def edit (id):
#Getting user by primary key:
post = Post.query.get(id)
if request.method == 'POST':        
    post.title = request.form['title']
    post.text =  request.form['text']
    db.session.commit()
    flash('New entry was successfully posted')     

return redirect(url_for('edit',  id=id, post=post))

Update: Solved http://techarena51.com/index.php/flask-sqlalchemy-tutorial/ 更新:解决了http://techarena51.com/index.php/flask-sqlalchemy-tutorial/

I presume you only want to redirect if the user submitted a POST request? 我假设您仅在用户提交POST请求时才想重定向? I think your code should be: 我认为您的代码应为:

@app.route('/edit/<id>' , methods=['POST', 'GET'])
def edit (id):
#Getting user by primary key:
post = Post.query.get(id)
if request.method == 'POST':        
    post.title = request.form['title']
    post.text =  request.form['text']
    db.session.commit()
    flash('New entry was successfully posted')     
    return redirect(url_for('edit',  id=id, post=post))

# The rest of this code is executed when a GET is performed
return render_template("edit.html",id=id, post=post)

otherwise, yes, your current code will redirect to the same route every time it is accessed. 否则,是的,您的当前代码每次访问都会重定向到相同的路由。 I've updated my example to show how you need to render the edit template when the request method is not POST. 我已经更新了示例,以显示当请求方法不是POST时,如何呈现编辑模板。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM