Question about asyncio

Frank Millman frank at chagford.com
Tue Jun 17 03:09:20 EDT 2014


"Ian Kelly" <ian.g.kelly at gmail.com> wrote in message 
news:CALwzidmzG_WA5shw+PS4Y976M4DVTOwE=zb+KurVCpj3n+5wxQ at mail.gmail.com...
> On Fri, Jun 13, 2014 at 5:42 AM, Frank Millman <frank at chagford.com> wrote:
>> Now I want to use the functionality of asyncio by using a 'yield from' to
>> suspend the currently executing function at a particular point while it
>> waits for some information.
[...]
>
> If the caller needs to wait on the result, then I don't think you have
> another option but to make it a coroutine also.  However if it doesn't
> need to wait on the result, then you can just schedule it and move on,
> and the caller doesn't need to be a coroutine itself.  Just be aware
> that this could result in different behavior from the threaded
> approach, since whatever the function does after the scheduling will
> happen before the coroutine is started rather than after.

Thanks for the info, Ian. It confirms that I am on the right track by 
converting all functions involved in responding to an HTTP request into a 
chain of coroutines. I don't know if there is any overhead in that but so 
far the response times feel quite crisp.

It took me a while to actually implement what I wanted to do, but I now 
realise that I had not got my head around the 'async' way of thinking. It is 
coming clearer, and I now have a toy example working. For the record, this 
is what I am trying to accomplish.

I have a server, written in python, listening for and responding to HTTP 
requests. I have a browser-based client, written in Javascript. Once past 
the opening connection, all subsequent communication is carried out by 
XMLHttpRequests (Ajax).

Action by a user can trigger one or more messages to be sent to the server. 
They are joined together in a list and sent. The server unpacks the list and 
processes the messages in sequence. Each step in the process can generate 
one or more responses to be sent back to the client. Again they are built up 
in a list, and when the final step is completed, the entire list is sent 
back.

This all works well, but I have now introduced a complication. At any point 
in the server-side process, I want to be able to send a message to the 
client to open a dialog box, wait for the response, and use the response to 
determine how the process must continue.

This was the main reason why I wanted to move to an 'async' approach. I 
create a Task to handle asking the question, and then use asyncio.wait_for() 
to wait for the response. So far it seems to be working.

Thanks for the assistance.

Frank






More information about the Python-list mailing list