Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Flask: asynchronous response to client

I'm using Flask to develop a web server in a python app. I'm achieving this scenario: the client (it won't be a browser) sends a request, the server does some long task in background and on completion sends the response back to the client asynchronously. Is it possible to do that?

like image 683
theMoonlitKnight Avatar asked Jan 21 '14 13:01

theMoonlitKnight


People also ask

Can Flask handle asynchronous?

Async functions require an event loop to run. Flask, as a WSGI application, uses one worker to handle one request/response cycle. When a request comes in to an async view, Flask will start an event loop in a thread, run the view function there, then return the result.

How do you make a Flask API asynchronous?

Creating asynchronous routes is as simple as creating a synchronous route: You just need to install Flask with the extra async via pip install "Flask[async]" . Then, you can add the async keyword to your functions and use await .

Is Flask synchronous or asynchronous?

Flask has been claimed as synchronous on many occasions, yet still possible to get async working but takes extra work.

Why is Flask not async?

The simple explanation is that Flask uses WSGI to service HTTP requests and responses which doesn't support asynchronous I/O. Asynchronous code requires a running event loop to execute, so Flask needs to get a running event loop from somewhere in order to execute an async view.


1 Answers

What you ask cannot be done with the HTTP protocol. Each request receives a response synchronously. The closest thing to achieve what you want would be this:

The client sends the request and the server responds with a job id immediately, while it also starts a background task for this long calculation.

The client can then poll the server for status by sending the job id in a new request. The response is again immediate and contains a job status, such as "in progress", "completed", "failed", etc. The server can also return a progress percentage, which the client can use to render a progress bar.

You could also implement web sockets, but that will require socket enabled server and client.

like image 158
Miguel Avatar answered Sep 28 '22 10:09

Miguel