Seth Nelson
Seth Nelson

Reputation: 2608

Flask function to call other flask functions in the same app?

I have several flask functions wired up such that I can call them at:

localhost:5000/FunctionA/inputs
localhost:5000/FunctionB/inputs
localhost:5000/FunctionC/inputs

I want functionC to be able to call FunctionA and FunctionB. How do I do this? When I try to write a call in FunctionC to call another (say, FunctionA), the call hangs indefinitely (understandable - FunctionC is waiting for itself to end so that the end-point is free to process the functionA request).

Upvotes: 2

Views: 2867

Answers (2)

Ricardo Cid
Ricardo Cid

Reputation: 11

This has been answered here: Handling multiple requests in Flask

But TLDR; you just need to set your run function like this:

app.run(threaded=True)

I'm assuming you are using the Flask server and need to run this while you are in development. For production check the options in the link above

Upvotes: 1

teechap
teechap

Reputation: 861

I'm not sure exactly what you're asking, but you could easily initiate a GET request client-side for functionA and functionB when the user visits functionC. AJAX lets you do this in the background without reloading the page. jQuery makes AJAX easy. In your Jinja template, just load jQuery like this:

<script src="//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js" ></script>

Then when the document has loaded (i.e. the user visits functionC and the page has rendered), just do this:

<script>
$(document).ready(function(){

    $.get("localhost:5000/FunctionA/inputs");
    $.get("localhost:5000/FunctionA/inputs");
});
</script>

The above code will just send a GET request to the URLs specified and ignore any response from them, but the jQuery documentation shows how to do something with the data your Flask app returns (for instance, get the response and send it into functionC as a URL variable).

If you really want to redirect the user to each view function server-side, all you have to do is use Flask's redirect function. Here's the documentation.

Hope this helps.

Upvotes: 0

Related Questions