相关疑难解决方法(0)

如何在协议循环中将协程打包为普通函数?

我正在使用asyncio作为网络框架.

在下面的代码中(low_level是我们的低级函数,mainblock是我们的程序入口,user_func是用户定义的函数):

import asyncio

loop = asyncio.get_event_loop()
""":type :asyncio.AbstractEventLoop"""


def low_level():
    yield from asyncio.sleep(2)


def user_func():
    yield from low_level()


if __name__ == '__main__':
    co = user_func()
    loop.run_until_complete(co)
Run Code Online (Sandbox Code Playgroud)

我想包装low_level正常函数而不是coroutine(compatibility等等),但是low_level在事件循环中.如何将其包装为正常功能?

python coroutine python-3.x python-asyncio

13
推荐指数
1
解决办法
5428
查看次数

Python asyncio任务收益率很低

我对如何asyncio在Python 3.4中使用该模块感到困惑.我有一个searching搜索引擎的API,并希望每个搜索请求可以并行或异步运行,这样我就不必等待一次搜索完成另一次搜索.

这是我的高级搜索API,用于使用原始搜索结果构建一些对象.搜索引擎本身正在使用某种asyncio机制,所以我不会打扰它.

# No asyncio module used here now
class search(object):
  ...
  self.s = some_search_engine()
  ...
  def searching(self, *args, **kwargs):
    ret = {}
    # do some raw searching according to args and kwargs and build the wrapped results
    ...
    return ret
Run Code Online (Sandbox Code Playgroud)

为了尝试异步请求,我编写了以下测试用例来测试如何将我的东西与asyncio模块进行交互.

# Here is my testing script
@asyncio.coroutine
def handle(f, *args, **kwargs):
  r = yield from f(*args, **kwargs)
  return r

s = search()
loop = asyncio.get_event_loop()
loop.run_until_complete(handle(s.searching, arg1, arg2, ...))
loop.close()
Run Code Online (Sandbox Code Playgroud)

通过运行pytest, …

python asynchronous python-asyncio

13
推荐指数
1
解决办法
7829
查看次数

异步-同步-在一个python事件循环中异步调用

假设我有一个内部使用asyncio循环且没有异步接口的类:

class Fetcher:
    _loop = None
    def get_result(...):
        """
        After 3 nested sync calls async tasks are finally called with *run_until_complete*
        """
        ...
Run Code Online (Sandbox Code Playgroud)

我在内部使用asyncio的所有优点,而不必在外部代码中关心它。

但是然后我想Fetcher在一个事件循环中调用3个实例。如果我有async def界面,那就没有问题:asyncio.gather可以帮助我。如果不同时支持两个接口,是否真的没有其他方法可以做到?来吧!它使您由于一次异步使用而更改了所有项目。告诉我这不是真的。

python python-3.x python-asyncio aiohttp

5
推荐指数
1
解决办法
5497
查看次数