Skip to main content
 首页 » 编程设计

python之Flask 重定向到 url 并传递查询字符串

2025年05月04日23mayingbao

我有一个这样定义的 View :

@views.route('/issues') 
def show_view(): 
    action = request.args.get('action') 
method = getattr(process_routes, action) 
return method(request.args) 

在我的 process_routes 模块中,我想调用这个方法,并传递查询字符串值。我有以下代码:

return redirect(url_for('views.show_view', action='create_or_update_success')) 

我在 process_routes 中有一个名为 create_or_update_success 的函数

我得到了

BuildError: ('views.show_view', {'action': 'create_or_update_success'}, None) 

View 是一个蓝图。我可以成功调用

/issues?action=create_or_update_success 

在我的浏览器中。

我做错了什么?

请您参考如下方法:

第一部分,views.,必须准确反射(reflect)您为 Blueprint() 对象提供的第一个参数。

不要试图将第一个参数设置为 __name__,因为在包内时它很可能包含模块的完整路径。在你的情况下,我怀疑是 some_package.views 而不仅仅是 views。

为 Blueprint() 第一个参数改用字符串文字:

views_blueprint = Blueprint('views', __name__) 

因此您可以引用 url_for('views.show_view') 而不会出现构建错误。