Last active
March 8, 2021 00:09
-
-
Save Martlark/da45701d60fdd1511978fb6722b0c8fd to your computer and use it in GitHub Desktop.
Flask Decorator to auto convert request arg to a method parameter
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
def request_arg(arg_name, arg_type=str, arg_default=None): | |
""" | |
decorator to auto convert arg or form fields to | |
named method parameters with the correct type | |
conversion | |
@route('/something/<greeting>/') | |
@request_arg('repeat', int, 1) | |
def route_something(greeting='', repeat): | |
return greeting * repeat | |
# /something/yo/?repeat=10 | |
# yoyoyoyoyoyoyoyoyoyo | |
:param arg_name str: name of the form field or arg | |
:param arg_type lambda: (optional) the type to convert to | |
:param arg_default any: (optional) a default value. Use '' or 0 when allowing optional fields | |
:return: a decorator | |
""" | |
def decorator(f): | |
@wraps(f) | |
def decorated(*args, **kwargs): | |
form_value = request.form.get(arg_name) | |
arg_value = request.args.get(arg_name) | |
if form_value: | |
arg_value = form_value | |
if not arg_value: | |
arg_value = arg_default | |
if arg_value is not None: | |
try: | |
arg_value = arg_type(arg_value) | |
except Exception as e: | |
abort(400, Response(f"""Required argument failed type conversion: {arg_name}, {str(e)}""")) | |
kwargs[arg_name] = arg_value | |
return f(*args, **kwargs) | |
abort(400, Response(f"""Required argument missing: {arg_name}""")) | |
return decorated | |
return decorator |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment