from functools import wraps
from http.cookies import SimpleCookie
from typing import Any, Callable, Dict, Optional
def bind_request_header_args(
func: Callable,
header_name: str,
args: list[str],
fallback: Optional[Any] = None,
) -> Callable:
"""
Binds arguments from a request header to a function,
with fallback logic if the header is not present or the arguments are invalid.
"""
@wraps(func)
def wrapper(*args_func, **kwargs):
header_value = kwargs.get("headers", {}).get(header_name)
if not header_value:
if fallback is not None:
return fallback # Use fallback value
else:
return func(*args_func, **kwargs) # Call function without header args
try:
# Attempt to parse the header value as a list of arguments
parsed_args = [arg.strip() for arg in header_value.split(",") if arg.strip()]
except Exception:
# Handle potential parsing errors
if fallback is not None:
return fallback
else:
return func(*args_func, **kwargs)
# Check if the parsed arguments are valid
if len(parsed_args) != len(args):
if fallback is not None:
return fallback
else:
return func(*args_func, **kwargs)
# Bind the arguments to the function
bound_args = dict(zip(args, parsed_args))
return func(*args_func, **bound_args, **kwargs)
return wrapper
if __name__ == "__main__":
# Example Usage:
@bind_request_header_args(
header_name="my-args", args=["arg1", "arg2", "arg3"], fallback="default_value"
)
def my_utility_function(arg1: str, arg2: str, arg3: str, extra_arg: str = "default"):
"""
A sample utility function that accepts arguments from a request header.
"""
print(f"arg1: {arg1}, arg2: {arg2}, arg3: {arg3}, extra_arg: {extra_arg}")
# Test cases
# Test case 1: Header present with all args
headers1 = {"my-args": "value1,value2,value3"}
result1 = my_utility_function(arg1="value1", arg2="value2", arg3="value3")
print(f"Result 1: {result1}")
# Test case 2: Header present with some args missing
headers2 = {"my-args": "value1,value2"}
result2 = my_utility_function(arg1="value1", arg2="value2")
print(f"Result 2: {result2}")
# Test case 3: Header present with extra args
headers3 = {"my-args": "value1,value2,value3,value4"}
result3 = my_utility_function(arg1="value1", arg2="value2", arg3="value3", extra_arg="test")
print(f"Result 3: {result3}")
# Test case 4: Header not present, using fallback
headers4 = {}
result4 = my_utility_function()
print(f"Result 4: {result4}")
# Test case 5: Invalid header value
headers5 = {"my-args": "invalid_value"}
result5 = my_utility_function()
print(f"Result 5: {result5}")
Add your comment