async def和coroutines,链接是什么

时间:2016-03-04 12:44:01

标签: python-3.x python-asyncio

我正试图围绕Python3中出现的新的asyncio功能。

我从一个在stackoverflow上找到的简单工作者示例开始,修改了一下:

import asyncio, random

q = asyncio.Queue()

@asyncio.coroutine
def produce(name):
    while True:
        value = random.random()
        yield from q.put(value)
        print("Produced by {0}".format(name))
        yield from asyncio.sleep(1.0 + random.random())

@asyncio.coroutine
def consume(name):
    while True:
        value = yield from q.get()
        print("Consumed by {0} ({1})".format(name, q.qsize()))
        yield from asyncio.sleep(1.2 + random.random())

loop = asyncio.get_event_loop()
loop.create_task(produce('X'))
loop.create_task(produce('Y'))
loop.create_task(consume('A'))
loop.create_task(consume('B'))
loop.run_forever()

我主要理解它是如何工作的(除了yield from asyncio.sleep()之外......它是一个委托但阻塞函数的占位符吗?它在哪里产生?)

但最重要的是,我如何将此示例转换为使用新的花哨async defawait关键字?会有什么好处?

2 个答案:

答案 0 :(得分:3)

答案 1 :(得分:2)

只需替换

  string json = JsonConvert.SerializeObject(item);
                    var content = new StringContent(json, Encoding.UTF8, "application/json");
                    HttpResponseMessage response = null;
                    response = await client.PostAsync(url, content);

@asyncio.coroutine
def f(arg)

async def f(arg) 代码中包含yield from

另请阅读PEP 412关于awaitasync with