2016-07-19 90 views
4

我正在編寫應用程序,它每秒掃描一次目錄,檢查新文件,如果它們出現 - 通過POST請求發送它們並執行歸檔。假設可以出現在目錄中的文件數量可以從10到100 - 我決定使用asyncio和aiohttp同時發送請求。asyncio。動態添加協程循環

代碼:

import os 
import aiohttp 
from aiohttp.client import ClientSession 

BASE_DIR = '/path/to' 
ARCHIVE_DIR = '/path/to/archive' 

async def scan(): 
    while True: 
     await asyncio.sleep(1) 
     for file in os.listdir(BASE_DIR): 
      if os.path.join(BASE_DIR, file).endswith('jpg'): 
       asyncio.ensure_future(publish_file(file)) 


async def publish_file(file): 
    async with ClientSession(loop=loop) as session: 
     async with session.post(url=url, data={'photo': open(os.path.join(BASE_DIR, file), 'rb')}) as response: 
      if response.status == 200: 
       await move_to_archive(file) 

async def move_to_archive(file): 
    os.rename(os.path.join(BASE_DIR, file), os.path.join(ARCHIVE_DIR, file)) 

loop = asyncio.get_event_loop() 

coros = [ 
    asyncio.ensure_future(scan()) 
] 
loop.run_until_complete(asyncio.wait(coros)) 

因此問題是:如果我要發送的請求的併發,這是一個很好的做法,協同程序添加到循環是這樣的:asyncio.ensure_future(publish_file(file))

回答

5

是的,它是正確的。

P.S.更好地共享相同的會話(可能是數量有限的並行連接),而不是在每個帖子請求中重新創建連接池:

session = aiohttp.ClientSession(connector=aiohttp.TCPConnector(limit=10))