Flask blueprints routes double dot issue

Viewed 421

I'm building a pretty basic Python-Flask app. In order not get get my code too cluttered I wanted to divide the routes into separate files related to specific features (e.g. user management) using Blueprints. Following code works fine:

The app.py:

from user_routes import usr_routes
app = Flask(__name__)
app.register_blueprint(usr_routes, url_prefix="/")

The user_routes.py

from flask import Blueprint

usr_routes = Blueprint("", __name__)

@usr_routes.route("/users")
def users():
    return "Not implemented yet"

The menu.html:

<li class="nav-item dropdown">
            <a class="nav-link dropdown-toggle" href="#" id="navbarDropdown" role="button" data-bs-toggle="dropdown" aria-expanded="false">
              Users
            </a>
            <ul class="dropdown-menu" aria-labelledby="navbarDropdown">
              <li><a class="dropdown-item" href="{{url_for('..users')}}">Users</a></li>
              <li><a class="dropdown-item" href="{{url_for('new_user')}}">New User</a></li>
              <li><hr class="dropdown-divider"></li>
            </ul>
          </li>

Folder structure:

Project
|--app.py
|--user_routes.py
|--templates
|  |-menu.html
|  |-base.html

Question: Why do I need to add two dots in the HTML file in front of users? If I don't I get following error: werkzeug.routing.BuildError: Could not build url for endpoint users. Did you mean .users?

1 Answers

Relative imports make use of dot notation to specify location. A single dot means that the module or package referenced is in the same directory as the current location. Two dots mean that it is in the parent directory of the current location—that is, the directory above.

Related