デコレータを使用して関数に到着するパラメータ(辞書オブジェクトを介して)を検証しています.2つ以上のキーがあるとうまく動作します。しかし、キーだけを持っていればエラー(check_person)を返します。それを動作させるためにPython Decoratorのバリデーション
if _NAME in json_request:
return True
return False
:私はcheck_personを変更する必要が
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
:私は私の問題を例示するために2つの機能を定義しました。
私は試してみてください。
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のように)正常に動作している場合。