【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/

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM