0

I am using Flask. I want to call a function using globals.

I make an API call using parameters passed as a dictionary:

my_parameters = {
    "function" : "add_numbers",
    "number_1" : 100,
    "number_2" : 200
}

I can call the function in Flask as follows:

@app.route("/call_my_function/", methods=["GET"])
    def call_my_function():
        res = globals()[request.args.get('function')](100, 200)
        return(res)

...which works fine, but as you can see I am harcoding the 100 and 200 arguments. I want these arguments to be passed from the my_parameters dictionary. I tried this:

@app.route("/call_my_function/", methods=["GET"])
    def call_my_function():
        res = globals()[request.args.get('function')](list(args.values())[1:])
        return(res)

But the arguments are not accepted in globals. It says:

TypeError: add_numbers() missing 1 required positional argument
Cybernetic
  • 12,628
  • 16
  • 93
  • 132
  • Using tuple *unpack* should do the magic: `globals()[request.args.get('function')](*args.values())` – metmirr Dec 08 '19 at 20:26
  • This doesn't remove the "function" argument from the parameter object. Is there a way to remove the first element from the *args.values()? In other words, this gives the "takes 2 positional arguments but 3 were given" error. Problem being tuples are immutable. – Cybernetic Dec 08 '19 at 20:29
  • 1
    First get values as list `values = list(args.values())[1:]` then pass as tuple `globals()[request.args.get('function')](*tuple(values))` – metmirr Dec 08 '19 at 20:39
  • That was it. Thank you! – Cybernetic Dec 08 '19 at 20:42
  • Happy to hear that :) – metmirr Dec 08 '19 at 20:43

0 Answers0