0

I need help with the python web framework, Quart. I want to build a python server that returns 202 as soon as a client requests some time consuming I/O task, and call the client back to return value of that task as soon as the task is done.

For that purpose, I add task requested by client to the background task using app.add_background_task(task) and that gave me a successful result as it returns 202 immediately. But I'm not sure how I can approach the return value of background task and call the client back to give that value.

I'm reading https://quart.palletsprojects.com/en/latest/how_to_guides/server_sent_events.html this article. But I'm not sure how to handle it.

async def background_task(timeout=10):
    print(f"background task started at", str(datetime.now().strftime("%d/%m/%Y %H:%M:%S")))
    await asyncio.sleep(timeout) 
    print(f"background task completed at", str(datetime.now().strftime("%d/%m/%Y %H:%M:%S")))
    return "requested task done"

@app.route("/", methods=["GET"])
async def main_route():
    print("Hello from main route")
    app.add_background_task(background_task, 10)
    return "request accepted", 202

1 Answers1

0

To push information to the client, you'll need Websockets or some other mechanism - it'll require server and client-side implementations

A simpler solution is to poll the server from the client to determine if the task is complete or not. i.e. send requests repeatedly to the server until you get confirmation of what you expect, or your max number of attempts is exceeded (or a request just times out entirely)

Larry
  • 1,238
  • 2
  • 20
  • 25
  • Yes, as you said I need Websockets, and as far as I know, Quart has its own websocket decorator. But what I want to know is how to approach background tasks' return value. – yunrori Oct 06 '22 at 09:47
  • One approach is to persist the return value in storage and query it periodically (polling). Alternatively, it may be a good idea to investigate how Quart emits events or signals: when the task completes, emit a signal with the return value, and then somewhere else in the application have a listener handle that event, doing whatever you wish with it - pushing to a websocket client, persisting to storage, sending emails, etc. – Larry Oct 06 '22 at 16:48