Home > Back-end >  How to apply multiple methods on the same data element in FastAPI
How to apply multiple methods on the same data element in FastAPI

Time:06-02

I want to perform the following processing of a String variable received as a parameter of my API endpoint (FastAPI) as shown below, and I have 30 functions that need to be applied to the String variable. I'm kind of lost and don't really know how can I do this, any hints, or concepts I should learn about that can help solve the problem.


Code:

 
def func1(data):
    return True
def func2(data):
    return True
def func3(data):
    return True
...

def func30(data):
    return True


@app.get("/process/{data}")
def process(data):
    # Apply all the methods on the data variable 
    return response ```

----------


thank you

CodePudding user response:

You can use map with a list of functions and turn it into a list, as map is lazily evaluated. You may ignore the list if not needed.

def apply(data, functions):
    return list(map(lambda f: f(data), functions))

CodePudding user response:

you can create a new function that iterates over the other ones either by inserting the other functions as inputs, or by getting them using only the pattern and their ids, here's a code for the second idea : (I used the globals() function to get the functions since they are defined in the same module, if not use getattr() instead)

def func1(data):
    return data   'a'

def func2(data):
    return data   'b'

def func3(data):
    return data   'c'

def func4(data):
    return data   'd'

def apply_funcs(func_id_list, func_pattern, data):
    """Apply multiple functs that have indexes in func_id_list and with the func_pattern pattern"""
    # init output
    output = data

    # Apply the different functions
    for id in func_id_list:
        output = globals()[f'{func_pattern}{id}'](output)

    return output

# test
data = 'test_'
print(apply_funcs([1, 2, 3, 4], 'func', data))

output:

test_abcd
  • Related