Skip to main content
 首页 » 编程设计

python/flask 构建错误与 url_for,额外的无

2025年05月04日13mate10pro

我不知道额外的 None 是从哪里来的。我试过这些链接无济于事:Build error with variables and url_for in Flask how to use Flask Jinja2 url_for with multiple parameters

此外,我不使用BluePrint。

这是我的 users.html 模板:

<a href="{{ url_for('user_page', user_id=user.user_id) }}"> {{ user.name }} </a> 

这是我试过的两个不同的 user.py 文件:

@app.route('/user') 
def user_page(): 
    args = show_user_parser.parse_args() 
    user_id = args['user_id'] 
    return page_for_user(user_id) 
 
@app.route('/user/<user_id>') 
def user_page(user_id): 
    return page_for_user(user_id) 
 
def page_for_user(user_id): 
   try: 
       cur.execute(list_user_detailed_query, (user_id,)) 
   except psycopg2.OperationalError: 
       return render_template('error.html') 
   except psycopg2.IntegrityError: 
       connection.rollback() 
       return render_template('error.html') 
   data = cur.fetchone() 
   return render_template('user.html', 
                          name=data['name'], 
                          email=data['email'], 
                          undergrad=data['undergrad'], 
                          cv=data['cv']) 

这是构建错误:

BuildError: ('user_page', {'user_id': '1'}, None) 

请您参考如下方法:

您已将两条路线命名为“user_page”,所以我敢打赌第一个(不带参数)获胜,当您尝试构建带参数的 url 时,它会失败。重命名函数,使它们不同,这应该可以修复它。