Flask的url_for生成了错误的URL

3

在Flask中,url_for生成器不能为我的某个视图(其他视图可以正常工作)工作。生成器提供了/user/?name=Joe,但我预期的是/u/Joe

在模板中,我尝试使用以下方式获取用户页面的URL:{{ url_for('user', name = g.user.name ) }}

下面是对应的视图函数:

@app.route('/u/<name>')
@login_required
def user(name):

起初这个功能是可行的,但后来发生了什么变化。我尝试更改视图名称和url,但没有成功。
你有什么想法吗?对于这个问题我束手无策...
完整的应用程序可以在GitHub上找到:https://github.com/joehand/weight-and-more-tracker 另外,移除<name>变量并不能解决问题。URL将只是/user编辑:被装饰为@login_required的函数是Flask-login提供的。
2个回答

3
在api.py中,您正在注册一个名为“user”的视图,这可能与名为“user”的方法发生冲突。

这绝对是问题的原因 - Flask默认使用提供给它的函数的__name__注册路由。但是,如果提供了两个具有相同名称的条目,则最后提供的条目将获胜。Flask-MongoRest使用add_url_rule向Flask注册自己,并使用name关键字参数告诉Flask要在其下注册什么。因此,user函数被user MongoRest类覆盖。 - Sean Vieira
谢谢!!!问题已解决。我会确保为API路由使用更具体的名称。 - joehand

0

你是否在函数中使用了 login_required 装饰器?在你的情况下,name 是作为查询字符串提供到 URL 中的,而不是作为 Flask 视图函数参数 - 可能 Flask 没有掌握你装饰的 user 视图函数的参数规范。

来自 文档

So let’s implement such a decorator. A decorator is a function that returns a function. Pretty simple actually. The only thing you have to keep in mind when implementing something like this is to update the name, module and some other attributes of a function. This is often forgotten, but you don’t have to do that by hand, there is a function for that that is used like a decorator (functools.wraps()).

from functools import wraps
from flask import g, request, redirect, url_for

def login_required(f):
    @wraps(f)
    def decorated_function(*args, **kwargs):
        if g.user is None:
            return redirect(url_for('login', next=request.url))
        return f(*args, **kwargs)
    return decorated_function

@login_required 装饰器是 Flask-Login 扩展提供的。移除装饰器并不能解决任何问题。 - joehand

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接