A question about blueprints and routing in flask

this afternoon, I wrote an ajax request and response method, something like this:

<script type="text/javascript">
    $(function () {
        $.get("{{ url_for("blueprint.api") }}", function (data) {
           console.log(data.test);
        });
    });
    </script>
@blueprint.route("/api", methods=["GET"])
def api():
    return jsonify("test": "success")

to test it, I thought there would be no problem. Result:

Failed to load resource: the server responded with a status of 404 (NOT FOUND)

Why?
after some investigation, it is finally determined that the route is written incorrectly.
when using blueprints, write a statement like this:

app.register_blueprint(blueprint, url_prefix="/")
The

problem lies in the parameter url_prefix . Remove this parameter and you can pass the test. However, I thought of another situation, so I retained the parameter url_prefix and modified rule :

instead.
@blueprint.route("api", methods=["GET"])
def api():
    return jsonify("test": "success")

also passed the test.
when using blueprints, you can use the url_for method to get the path.

  1. when url_prefix="/" , rule="/api" , url_for method output / api , the request fails (Not
    Found);
  2. when url_prefix="/" , rule="api" , url_for method output / api , the request is successful;
  3. when url_prefix=None or url_prefix="" , rule="/api" , url_for method outputs / api , the request is successful.

the question is, why did case 1 fail the request?

Mar.18,2021

-sharp 
-sharp from flask.blueprints import Blueprint
-sharp 
def add_url_rule(self, rule, endpoint=None, view_func=None, **options):
  """A helper method to register a rule (and optionally a view function)
  to the application.  The endpoint is automatically prefixed with the
  blueprint's name.
  """
  if self.url_prefix:
    rule = self.url_prefix + rule
  options.setdefault('subdomain', self.subdomain)
  if endpoint is None:
    endpoint = _endpoint_from_view_func(view_func)
  defaults = self.url_defaults
  if 'defaults' in options:
    defaults = dict(defaults, **options.pop('defaults'))
  self.app.add_url_rule(rule, '%s.%s' % (self.blueprint.name, endpoint),
                        view_func, defaults=defaults, **options)
                        
-sharp 1 //api
-sharp  //api  /* 
Menu