【Flask】报错解决方法:AssertionError: View function mapping is overwriting an existing endpoint function: main.user

  

  运行Flask时出现了一个错误, AssertionError: View function mapping is overwriting an existing endpoint function: main.user

  直译就是视图方法中重写了一个存在的endpoint方法。那么问题来了,endpoint 是何方神圣?

  查看了下源码,它的本质其实是请求url的一个规则,用来标记请求之后由哪个方法去具体执行。

 

@property
def endpoint(self):
    """The endpoint that matched the request.  This in combination with
    :attr:`view_args` can be used to reconstruct the same or a
    modified URL.  If an exception happened when matching, this will
    be ``None``.
    """
    if self.url_rule is not None:
        return self.url_rule.endpoint

  

  Flask官方文档中的解释:

endpoint(endpoint)

A decorator to register a function as an endpoint. Example:

@app.endpoint('example.endpoint')
def example():
    return "example"

Parameters:	endpoint – the name of the endpoint

  

  以及其他函数中的用法,例如:add_url_rule()

add_url_rule(rule, endpoint=None,...)

Parameters:	
#...
endpoint – the endpoint for the registered URL rule. Flask itself assumes the name of the view function as endpoint

  

      敲黑板划重点,Flask的默认endpoint其实就是视图模块中的各个具体方法名。

 

  弄明白了endpoint,重新review下代码,发现确实是定义了相同方法名。

#...

@main.route('/user/<name>')
def user(name):
     return render_template('user_simple.html',name=name)

#...

@main.route('/user/<username>')
def user(username):
    user = User.query.filter_by(username=username).first_or_404()
    return render_template('user.html',user=user)

  

  找到问题根因,解决方法就so easy了,重命名其中一个方法名即可,问题搞定✿✿ヽ(°▽°)ノ✿

 

参考文档:http://flask.pocoo.org/docs/1.0/api/

 

posted @ 2019-04-19 18:07  LiliP  阅读(10483)  评论(0编辑  收藏  举报