Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to apply multiple methods on the same data element in FastAPI

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading