There is a function in the application on Python that makes four get-requests, then assigns their answers to variables and then processes these variables. This happens synchronously. Is it possible to run these four requests to be processed simultaneously asynchronously, and then put the function on "pause" until all of them return the result? Those. to actually write synchronously asynchronous code.

Application on the Tornado framework

  • one
    request code runs in separate threads. And the main thread simply starts them all first and makes join. - KoVadim

1 answer 1

(Small disclaimer : see Tornado and its documentation for the first time)

  • If I understand correctly, then your task is elegantly solved with the help of tornado.gen, which uses futures for parallel execution of subtask'ов and the syntax based on yield:

     @web .asynchronous @gen .coroutine def perform_requests_and_handle_them(self): client = AsyncHTTPClient() # В вашем случае здесь будет 4 параллельно # выполняющихся операции. response1, response2 = yield [client.fetch(url1), client.fetch(url2)] # Здесь вы синхронно обрабатываете результат асинхронно # выполненных запросов. synchronously_handle_responses(response1, response2) 
  • If the documentation is correct, then this code does exactly what you described in your problem statement:

  • Most asynchronous functions in Tornado return a Future ; yielding this object returns its result.

  • You can also make a list of Futures and / or Tasks , when they are all finished.

  • A few additional references on the topic: