1. from functools import wraps
  2. from http.cookies import SimpleCookie
  3. from typing import Any, Callable, Dict, Optional
  4. def bind_request_header_args(
  5. func: Callable,
  6. header_name: str,
  7. args: list[str],
  8. fallback: Optional[Any] = None,
  9. ) -> Callable:
  10. """
  11. Binds arguments from a request header to a function,
  12. with fallback logic if the header is not present or the arguments are invalid.
  13. """
  14. @wraps(func)
  15. def wrapper(*args_func, **kwargs):
  16. header_value = kwargs.get("headers", {}).get(header_name)
  17. if not header_value:
  18. if fallback is not None:
  19. return fallback # Use fallback value
  20. else:
  21. return func(*args_func, **kwargs) # Call function without header args
  22. try:
  23. # Attempt to parse the header value as a list of arguments
  24. parsed_args = [arg.strip() for arg in header_value.split(",") if arg.strip()]
  25. except Exception:
  26. # Handle potential parsing errors
  27. if fallback is not None:
  28. return fallback
  29. else:
  30. return func(*args_func, **kwargs)
  31. # Check if the parsed arguments are valid
  32. if len(parsed_args) != len(args):
  33. if fallback is not None:
  34. return fallback
  35. else:
  36. return func(*args_func, **kwargs)
  37. # Bind the arguments to the function
  38. bound_args = dict(zip(args, parsed_args))
  39. return func(*args_func, **bound_args, **kwargs)
  40. return wrapper
  41. if __name__ == "__main__":
  42. # Example Usage:
  43. @bind_request_header_args(
  44. header_name="my-args", args=["arg1", "arg2", "arg3"], fallback="default_value"
  45. )
  46. def my_utility_function(arg1: str, arg2: str, arg3: str, extra_arg: str = "default"):
  47. """
  48. A sample utility function that accepts arguments from a request header.
  49. """
  50. print(f"arg1: {arg1}, arg2: {arg2}, arg3: {arg3}, extra_arg: {extra_arg}")
  51. # Test cases
  52. # Test case 1: Header present with all args
  53. headers1 = {"my-args": "value1,value2,value3"}
  54. result1 = my_utility_function(arg1="value1", arg2="value2", arg3="value3")
  55. print(f"Result 1: {result1}")
  56. # Test case 2: Header present with some args missing
  57. headers2 = {"my-args": "value1,value2"}
  58. result2 = my_utility_function(arg1="value1", arg2="value2")
  59. print(f"Result 2: {result2}")
  60. # Test case 3: Header present with extra args
  61. headers3 = {"my-args": "value1,value2,value3,value4"}
  62. result3 = my_utility_function(arg1="value1", arg2="value2", arg3="value3", extra_arg="test")
  63. print(f"Result 3: {result3}")
  64. # Test case 4: Header not present, using fallback
  65. headers4 = {}
  66. result4 = my_utility_function()
  67. print(f"Result 4: {result4}")
  68. # Test case 5: Invalid header value
  69. headers5 = {"my-args": "invalid_value"}
  70. result5 = my_utility_function()
  71. print(f"Result 5: {result5}")

Add your comment