async 异步协程的一次实践

需求是要发送多次请求获取数据,时间太慢 所以使用异步协程来解决 Python版本3.5

一开始是单独写了一个文件运行没有问题

import asyncio
import json
import aiohttp
from IFS.settings import AUTH_URL_ADDRESS

department_ids = [2, 3, 4]
list_seller = []


async def get_department_users1(department_id):
    global list_seller
    url = '{}api/departments/{}/users/'.format(AUTH_URL_ADDRESS, department_id)
    async with aiohttp.ClientSession() as session:
        async with await session.get(url) as response:
            content = await response.text('utf-8')
            json_res = json.loads(content)
    list_seller += json_res.get('data')


if __name__ == "__main__":
    # start_time = time.time()

    task_list = [get_department_users1(department_id) for department_id in department_ids]

    loop = asyncio.get_event_loop()
    loop.run_until_complete(asyncio.wait(task_list))

    print(len(list_seller), 111)

然后移植到项目中 就报线程中没有这个loop

There is no current event loop in thread 'Thread 和loop argument must agree with Future

经过调试后 和修改代码 并封装后 后成功 

世上无难事 只要肯登攀

import asyncio
from IFS.settings import AUTH_URL_ADDRESS
import aiohttp

import json


def get_all_seller(department_ids):
    list_seller1 = []

    async def get_department_users1(department_id):
        """
        根据部门id 获取人员列表升级版本
        :param department_id: 部门id[]]
        :return: list ['张三',]
        """
        url = '{}api/departments/{}/users/'.format(AUTH_URL_ADDRESS, department_id)
        async with aiohttp.ClientSession() as session:
            async with await session.get(url) as response:
                content = await response.text('utf-8')
                json_res = json.loads(content)
                list_seller1.append(json_res.get('data'))

    task_list = [get_department_users1(department_id) for department_id in department_ids]
    new_loop = asyncio.new_event_loop()
    asyncio.set_event_loop(new_loop)
    new_loop.run_until_complete(asyncio.wait(task_list))
    all_list_seller = []

    for list_seller in list_seller1:
        if list_seller:
            all_list_seller += list_seller
    new_loop.close()
    return all_list_seller

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值