Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to call a method from a different blueprint in Flask?

Tags:

python

flask

I have an application with multiple blueprinted modules.

I would like to call a method (a route) that would normally return a view or render a template, from within a different blueprint's route.

How can this be done correctly?

Thank you.

like image 613
Phil Avatar asked Dec 15 '22 00:12

Phil


1 Answers

Views are just functions; import the function and call it directly, passing in any route parameters that it may have defined.

The role of the Blueprint is to make it easier to register a group of routes under a common prefix, group their templates and static resources, and handle request-related events for just that group (request started, request completed, etc.). But how you call a view doesn't change.

For example, if you have a route in the foo blueprint, in the foo.py module:

@foo.route('/bar/<id>')
def bar(id):
    return something_done_with_id(id)

you can import that function and use it elsewhere:

import foo

@baz.route('/spam/ham/eggs'):
def baz():
    return foo.bar(42)

Here bar takes a parameter from the URL, named id, so when calling the view function we do need to pass in a value for that parameter.

Do note that any blueprint before_request, after_request and context_processor functions are not executed (that happens at routing time), nor are Blueprint-specific error handlers in effect.

like image 166
Martijn Pieters Avatar answered Dec 29 '22 00:12

Martijn Pieters