Skip to content

Instantly share code, notes, and snippets.

@rileypeterson
Last active February 1, 2019 01:25
Show Gist options
  • Save rileypeterson/643484d9c2df427cdf4aff19fa6480a4 to your computer and use it in GitHub Desktop.
Save rileypeterson/643484d9c2df427cdf4aff19fa6480a4 to your computer and use it in GitHub Desktop.
Just some musings about decorators
from functools import wraps
STRING1_LIST = ['A', 'B', 'C']
STRING2_LIST = ['D', 'E', 'F']
def type_checker(int1=None, string1=None, string2=None):
""" Decorator function to check if int1 is an int and
that string1 or string2 supplied is actually a valid string
"""
if string1:
s = 'string1'
list_to_find_in = STRING1_LIST
if string2:
s = 'string2'
list_to_find_in = STRING2_LIST
obj = string1 or string2
try:
int1 = int(int1)
except ValueError:
bottle.response.status = 400
return {"status": "error", "message": "int1 could not be converted to int."}
if obj not in list_to_find_in:
bottle.response.status = 400
return {"status": "error", "message": "Invalid {} name:{}. Must be one of:{}".format(s, obj, list_to_find_in)}
return None
def invalid_arg_catcher(your_type_checker_here):
""" Decorator to implement a type checker """
def decorator_outer(func):
@wraps(func)
def wrapper(*args, **kwargs):
caught = your_type_checker_here(**kwargs)
if caught:
return caught
return func(*args, **kwargs)
return wrapper
return decorator_outer
@app.get('/<int1>/<string1>')
@invalid_arg_catcher(type_checker)
@authentication_decorator
def _get(int1, string1):
@rileypeterson
Copy link
Author

Decorator to implement some custom type checking for a bottle endpoint.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment