1
我使用裝飾器來驗證參數到達我的功能(通過字典對象),當我有2個或更多的鍵時,它工作正常。但是,如果我只有密鑰它會返回一個錯誤(check_person)。我定義2個函數來舉例說明我的問題:Python裝飾器驗證
def required(**mandatory):
"""
:param mandatory:
:return:
"""
def decorator(f):
@wraps(f)
def wrapper(**dicts):
for argname, d in dicts.items():
for key in mandatory.get(argname, []):
if key not in d:
raise Exception('Key "%s" is missing from argument "%s"' % (key, argname))
return f(**dicts)
return wrapper
return decorator
@required(json_request=(_PROVIDER, _REPORT))
def check_campaign(json_request):
"""
:param json_request:
:return:
"""
return True
@required(json_request=(_NAME))
def check_person(json_request=None):
"""
:param json_request:
:return:
"""
return True
我需要改變check_person到:
if _NAME in json_request:
return True
return False
要使它發揮作用。
當我嘗試:
self.assertTrue(validator.check_person(json_request=json.loads("""{"name": "Elon Musk"}""")))
或具體爲:
{"name": "Elon Musk"}
我得到:
Error
Traceback (most recent call last):
File "/Users/spicyramen/Documents/OpenSource/Development/Python/gonzo/utils/validate/validator_test.py", line 46, in test_person
self.assertTrue(validator.check_person(json_request=json.loads("""{"name": "Elon Musk"}""")))
File "/Users/spicyramen/Documents/OpenSource/Development/Python/gonzo/utils/validate/validator.py", line 26, in wrapper
raise Exception('Key "%s" is missing from argument "%s"' % (key, argname))
Exception: Key "n" is missing from argument "json_request"
在我的字典裏有超過1個鍵,它工作正常(像check_campaign) 。