2017-05-05 47 views
0

我想從我的服務中進行API調用,並且遇到事件循環問題。有人能幫助我瞭解我做錯了什麼嗎?aiohttp:從正在運行的web.Application調用asyncio:RuntimeError:此事件循環已在運行

基本上我想做一個服務,根據從不同的服務中提取的數據做一些計算。

我可以調用下面這段代碼從CLI,而不是當我啓動了一個web應用程序(即)擊中http://127.0.0.1:8080/add

loop = asyncio.get_event_loop() 
data = loop.run_until_complete(run_fetch(loop, 'http://google.com')) 

示例代碼:

from aiohttp import web 
import aiohttp 
import asyncio 

async def add(request): 
    loop = asyncio.get_event_loop() 
    data = loop.run_until_complete(run_fetch(loop, 'http://google.com')) 
    return web.json_response(data) 


async def fetch(client, url): 
    async with client.get(url) as resp: 
     assert resp.status == 200 
     return await resp.text() 


async def run_fetch(loop, url): 
    async with aiohttp.ClientSession(loop=loop) as client: 
     html = await fetch(client, url) 
    return html 

app = web.Application() 
app.router.add_get('/add', add) 
web.run_app(app, host='127.0.0.1', port=8080) 

例外:

錯誤處理請求 回溯(最近一次調用最後一次): 文件「.../aiohttp/web_protocol.py」,第417行,起始 RESP =從self._request_handler(請求)收率

文件 「.../aiohttp/web.py」,線路289,在_handle RESP =產率從處理程序(請求)

文件」 .. ./sample.py「,第11行,添加data = loop.run_until_complete(run_fetch(loop,'http://google.com'))

文件」.../python3.6/asyncio/base_events.py「,第454行在run_until_complete self.run_forever()

文件 「.../python3.6/ASYNCIO/base_events.py」,線路408,在run_forever 提高RuntimeError(「事件循環已經運行」)

RuntimeError:此事件循環已經運行

回答

1

run_until_complete是運行在同步方面的一些異步代碼的方式。在引擎蓋下,它增加了給定的ioloop的未來,並調用run_forever然後返回結果或拋出異常(解決未來)。

其實你需要await run_fetch(loop, 'http://google.com'),因爲調用者函數是異步的。

+0

這是有道理的,並工作!謝謝! – user4445586