Reputation: 355
In Flask, how do you get a route value (eg. '/admin') inside a decorator? I need to pass certain string to the DB depending on which route was used (and they all use the same decorator).
@app.route('/admin')
@decorator
def admin(data):
do_something(data)
I couldn't find information about how to do it in Python. Is it possible?
Upvotes: 1
Views: 1558
Reputation: 3022
You can define a new decorator which get the current route path then do something with it:
from functools import wraps
from flask import request
def do_st_with_path(f):
@wraps(f)
def decorated_function(*args, **kwargs):
path = request.path
do_anything_with_path(path)
return f(*args, **kwargs)
return decorated_function
And for every route, add this decorator as the second one:
@app.route('/admin')
@decorator
def admin(data):
do_something(data)
Another solution without adding a new decorator: use before_request
. Before each request, you can also check the route path:
@app.before_request
def before_request():
path = request.path
do_anything_with_path(path)
Upvotes: 1