Search code examples
pythonexeceval

How do I execute string python will be input by the users via web application


We have a webApplication(.net) and calcuationengine (Python)

  1. WebApplication: to show results and Python Formula to users/and write python Input Formulas
  2. calcuationengine : Calculate Formulas

The target solution is :Web application send a json file with code to be evaluated (or executed).

Can you give a option about Exec/eval

exemple formula

def calcul_Inf_monthly_rates(Input) :    
    try :
        output=np.array([(1+v)**(1/12)-1 for v in Input])
    except:
        logging.error("Inf_monthly_rates : Error Calcul")
        output=[]
    finally:
        return output

Solution

  • Let's say your json looks like:

    json_func = """{"func": len}"""
    # I used a simple len function for example
    

    You can use evel in the following way:

    executed_func = eval(json_func)["func"]
    # now you can run executed_func with params
    
    print(executed_func("Hello")) # will output: 5