Python装饰器检查可能包含列表的函数的所有参数

vlf7wbxs  于 2022-12-28  发布在  Python
关注(0)|答案(1)|浏览(145)

我尝试实现一个装饰器函数来净化mongoDB的参数,这是我目前所做的:

def sanitize(function_to_decorate):
    def wrapper(*args):
        for query in args:
            if any(elem in r'${/}\\' for elem in query):
                raise Exception('String contains invalid characters')
        function_to_decorate(*args)
    return wrapper

@sanitize
def test(arg, arg2, list):
    print (arg, arg2, list) 

test('Hi', 'Me', '1') # Passes
test('Hi', 'Me', '{1') # Fails
test('Hi',  'Hey', ['Me', '{1']) # Passes

这是有意义的,因为我只对所有参数迭代一次,但由于一些函数可能需要列表作为参数(比如,对于$in检查),这并不是普遍有用的。
如何深入查看列表中任意数量的列表?

def a(str, str, [] )
def b([], [] ,[])

我也不知道如何为关键字参数实现这一点,但这是装饰器特有的问题。

ftf50wuq

ftf50wuq1#

你可以把检测参数的责任交给一个递归检查参数的函数:

def rsanitize(args):
    for query in args:
        if isinstance(query, list):
            rsanitize(query)
        elif any(elem in r'${/}\\' for elem in query):
            raise Exception('String contains invalid characters')
    
def sanitize(function_to_decorate):
    def wrapper(*args):
        rsanitize(args)
        function_to_decorate(*args)
    return wrapper

现在,您的最终测试用例将正确地失败:

Traceback (most recent call last):
  File "D:\xxx\soRecursivelyTestLists.py", line 22, in <module>
    test('Hi',  'Hey', ['Me', '{1']) # Passes
  File "D:\xxx\soRecursivelyTestLists.py", line 12, in wrapper
    rsanitize(args)
  File "D:\xxx\soRecursivelyTestLists.py", line 6, in rsanitize
    rsanitize(query)
  File "D:\xxx\soRecursivelyTestLists.py", line 8, in rsanitize
    raise Exception('String contains invalid characters')
Exception: String contains invalid characters

相关问题