【问题标题】:python/flask Build Error with url_for, extra Nonepython/flask 使用 url_for 构建错误,额外无
【发布时间】:2014-05-14 23:29:49
【问题描述】:

我不知道额外的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)

【问题讨论】:

  • page_for_user() 函数有什么作用?你能显示它的代码吗?
  • 添加了代码,尽管它可能不相关,因为手动输入 /user/id 或 /user?user_id=... 工作正常。

标签: python flask jinja2 url-for


【解决方案1】:

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

【讨论】:

  • 我显示了两个代码 sn-ps,但实际上两者都没有同时注册。我会注释掉一个 def user_page: 在运行我的服务器时。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2012-02-19
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-03-09
相关资源
最近更新 更多