Get route value from inside a decorator

别来无恙 提交于 2019-12-10 11:39:17

问题


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?


回答1:


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)


来源:https://stackoverflow.com/questions/48458780/get-route-value-from-inside-a-decorator

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!