本文介绍了从装饰器内部获取路由值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在Flask中,如何在装饰器中获取路由值(例如'/admin')?我需要根据使用的路由将某些字符串传递给数据库(它们都使用相同的装饰器).

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)

我找不到有关如何在Python中进行操作的信息.有可能吗?

I couldn't find information about how to do it in Python. Is it possible?

推荐答案

您可以定义一个新的装饰器,该装饰器获取当前的路径,然后对其进行处理:

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)


另一种无需添加新装饰器的解决方案:使用 before_request .在每个请求之前,您还可以检查路由路径:


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)

这篇关于从装饰器内部获取路由值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-27 15:40