需求是要发送多次请求获取数据,时间太慢 所以使用异步协程来解决 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