0

I am trying to implement a REST API in python using flask. However, the API implementation in turn needs to make some network calls (db for example). To improve throughput can I make this asynchronous? By that I mean this. Lets suppose teh REST API is foo()

def foo():
    # 1. do stuff as needed
    # 2. call make_network_call and wait for it to return.
    # 3. do stuff as needed with returned data.
    # 4. return.

Now if I know its going to take some time at step 2, can I give up the cpu here and process other incoming requests and come back to it when it returns? If so how do I do it and what are the frameworks involved? I am using python with flask currently.

3 Answers 3

1

Flask can be run with multiple threads or processes when it's launched, see this question. It wont make foo() any more efficient, but you will be able to serve multiple clients simultaneously.

To run it with multiple threads or processes, you can specify so in the Flask.run() keywords:

for threads:

if __name__ == '__main__':
    app.run(threaded=True)

Or for processes:

if __name__ == '__main__':
    app.run(processes=5) # Or however many you you may want.
Sign up to request clarification or add additional context in comments.

1 Comment

Running flask this way isn't recommened in production -- you are better off reading the deployment options: flask.pocoo.org/docs/deploying For example -- running flask as the wsgi backend to a NGINX server or similar.
1

If you're using a recent (>= 3.2) version of Python, you can use concurrent.futures. That would look like:

from concurrent.futures import ThreadPoolExecutor

def other_func():
    with ThreadPoolExecutor as executor:
        future = executor.submit(foo)
        # do other stuff
        return future.result()

Comments

1

Have a look at Klein -- its a flask / twisted hybrid -- twisted is an asynchronous reactor pattern framework that works at a lower level than you'd be used to in flask.

Klein is like a wrapper on top of twisted that acts very like Flask -- allows you to write deffered code using the reactor.

https://github.com/twisted/klein

2 Comments

This doesn't answer the question of how to solve the problem with flask, unless you're suggesting to use flask and twisted together. If that's the case, you didn't make the answer very clear.
FWIW, here is a blog post discussing the "issue" plus tutorial that demonstrates how to do asynch stuff from Klein request handlers: tavendo.com/blog/post/…

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.