fabfuel / circuitbreaker

Python "Circuit Breaker" implementation
Other
455 stars 53 forks source link

Is there a way to have dynamic naming of the circuit depending on function parameters? #29

Open sebathi opened 2 years ago

sebathi commented 2 years ago

It will be really impresive if you can do something like this:

def dynamic_naming(params):
      return "dynamic_" + params.param1

@circuit(name-handler=dynamicNaming)
def external_call(param1, param2):
      requests.get('.......')
pauloromeira commented 1 year ago

hey @sebathi it looks good indeed. right now it's not possible because per decorator the circuit is created by the time the function is declared.

but you could achieve that with a custom decorator:

from functools import wraps
from circuitbreaker import CircuitBreaker, CircuitBreakerMonitor

def dynamic_circuit(name_handler, **circuit_kwargs):
    def inner(function):
        @wraps(function)
        def wrapper(*args, **kwargs):
            name = name_handler(*args, **kwargs)
            cb = CircuitBreakerMonitor.get(name) or CircuitBreaker(name=name, **circuit_kwargs)
            return cb(function)(*args, **kwargs)
        return wrapper
    return inner

def dynamic_naming(*args, **kwargs):
    return "dynamic_" + args[0]

@dynamic_circuit(name_handler=dynamic_naming)
def external_call(param1, param2):
    requests.get('.......')

I hope my response still holds meaning to you or to others, despite the delay.