Last active
June 16, 2017 14:50
-
-
Save AndreaCrotti/3d6b69acc55b637d32865dbf2d7b1fd5 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
""" | |
Use functools to declare the specification of inputs and validate | |
them on the fly with decorator. | |
It also only currently works with keyword arguments only, just to keep | |
it simpler (and because enforcing them might be a good idea anyway). | |
""" | |
import functools | |
import voluptuous as V | |
MessageSchema = V.Schema({ | |
V.Required('to'): str, | |
V.Required('preserve_recipients'): bool, | |
}) | |
class InvalidField(Exception): | |
pass | |
class validate_input(object): | |
def __init__(self, **validators): | |
self.validators = validators | |
def __call__(self, func): | |
@functools.wraps(func) | |
def _wrapped(**kwargs): | |
new_kwargs = {} | |
for key, value in kwargs.items(): | |
try: | |
new_value = self.validators[key](value) | |
except V.Invalid as e: | |
raise InvalidField("Could not validate field %s, voluptuous error: %s" % (key, e.errors)) | |
else: | |
new_kwargs[key] = new_value | |
return func(**new_kwargs) | |
return _wrapped | |
@validate_input(message=MessageSchema) | |
def my_function(message): | |
print(message) | |
if __name__ == '__main__': | |
# working case | |
my_function(message={'to': 'hello@world', 'preserve_recipients': True}) | |
# mismatching type | |
my_function(message={'to': 'hello@world', 'preserve_recipients': 'true'}) | |
# missing required | |
my_function(message={'preserve_recipients': 'true'}) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment