2016-07-19 43 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))