Skip to content

Instantly share code, notes, and snippets.

@AndreaCrotti
Last active June 16, 2017 14:50
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save AndreaCrotti/3d6b69acc55b637d32865dbf2d7b1fd5 to your computer and use it in GitHub Desktop.
Save AndreaCrotti/3d6b69acc55b637d32865dbf2d7b1fd5 to your computer and use it in GitHub Desktop.
"""
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