0

I have a very simple aiohttp web server:

from aiohttp import web
import time

async def hello(request):
    time.sleep(2) # heavy calculations goes here
    return web.Response(text="Hello, world")

app = web.Application()
app.add_routes([web.get('/search', hello)])
web.run_app(app)

If a user (in his browser) requests '/search?query=xxx' many times within a short period, I can't do my "heavy calculation" as fast as the user requests it.

I would like to cancel old requests (and send a message to the user that his request has been cancelled) and only reply to the last request with the result of the calculation.

How can I do this?

I need this for a web page with "incremental search", so the user may send requests as fast as he can type. Is this even the proper way to tackle this?

XPlatformer
  • 1,148
  • 8
  • 18
  • 1
    You typically do that by creating a `Job` object and delegating it to some external process. Then you immediately return the `id` of the job to the user. Then the user waits for the result (via websockets? or long polling?). You can easily implement cancel and rerun as well if you want to. Also you should ensure that there's a timeout on the client side after which requests are sent (don't send request every time he presses a key), for example 200ms should be fine. – freakish Mar 06 '19 at 12:26
  • Also perhaps you want to optimize the search itself. Are you saying that it takes 2s? That's most likely too long for anyone. Unless it's some specific niche, like full document search? – freakish Mar 06 '19 at 12:33

0 Answers0