python 异步调用问题

如:
a文件有calss get_site(url)类
b文件主函数获取url,然后调用a文件的get_site类。
做下载的操作,但这个可能耗时,想用异步。
应该怎么写?
谢谢了

阅读 3.2k
2 个回答

asyncio module

aiohttp
和原生asyncio协程就行了啊,
最简单的生产者和消费者模型.

#!/usr/bin/env python
# -*- coding: utf-8 -*-

import asyncio
import aiohttp

# 生产者
async def get_url(url_queue):
    url = "https://segmentfault.com/q/1010000011061360"
    await url_queue.put(url)

# 消费者
async def get_site(url_queue):
    while True:
        url = await url_queue.get()
        async with aiohttp.ClientSession() as client:
            async with client.get(url) as response:
                assert response.status == 200
                body = await response.text()
                # doing xxxx
        url_queue.task_done()


async def run():
    url_queue = asyncio.Queue()
    await get_url(url_queue)
    # 创建100个协程的消费者
    workers = [loop.create_task(get_site(url_queue)) for _ in range(100)]
    # 堵塞队列直到全面url完成
    await url_queue.join()
    # 中止无限循环的消费者协程
    for worker in workers:
        worker.cancel()


loop = asyncio.get_event_loop()
loop.run_until_complete(run())
loop.close()
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
1 篇内容引用
推荐问题