Search code examples
flaskjinja2werkzeug

Flask werkzeug.routing.BuildError if endpoint method name not same as route


I am using Flask with blueprints to build routing endpoints. The following works fine:

@my_view.route('/send_email', methods=['GET', 'POST'])
def send_email():
    print(">>send_email()")

wtf form:

<form role="form" action="{{ url_for('my_view.send_email') }}" method="post">

However if I change the method name such as below, I get an error "werkzeug.routing.BuildError: Could not build url for endpoint 'my_view.send_email'."

@my_view.route('/send_email', methods=['GET', 'POST'])
def some_other_method_name():
    print(">>some_other_method_name()")

Why do I need to name the method to be the same as the route for this to work?


Solution

  • url_for uses the function name to construct the url path. change

    <form role="form" action="{{ url_for('my_view.send_email') }}" method="post">
    

    to

    <form role="form" action="{{ url_for('my_view.some_other_method_name') }}" method="post">
    

    and you should be good to go. See here for a great explanation on how flask routing works.