Reputation: 3498
I have routes for my rest service:
localhost/rest/get/user
localhost/rest/get/logs/username
localhost/rest/post/user
etc. I have them registered as blueprints like so:
app.register_blueprint(rest, url_prefix="/rest")
app.register_blueprint(rest_get, url_prefix="/rest/get")
app.register_blueprint(rest_post, url_prefix="/rest/post")
I want however, that both the /rest/get
routes and /rest/post
routes all pass also through the common /rest
route so that I can add some before_request checks to them. However this is not the case per default, the Flask just routes the request to the most specific one. How do I make it also look in to the parent route? So in rest.py
I have:
@rest.before_request
@jwt_required(locations=["headers"])
def before_request():
print("************************************************* in rest in before_request")
pass
However, it is ignored and just goes to the one in rest_get.py, which is:
rest_get = Blueprint("rest_get", __name__)
@rest_get.before_request
@jwt_required(locations=["headers"])
def before_request():
print("************************************ in rest_get in before_request")
pass
How do I do this?
Upvotes: 1
Views: 763
Reputation: 375
As I understand you perform certain operations in the common route and you would want your subroutes to perform these operations before executing the function corresponding to the subroute.
The easiest thing I can think of if to implement the common operation as a separate class or function and call it in every route, subroute etc
For example
@app.route("/rest")
def base():
response = common_operation()
return response.json()
@app.route("/rest/sr1")
def subroute1():
op = common_operation()
op1 = further_operations(op)
return op1
Something like this is what I do and suggest the same.
Upvotes: 1