我正在使用aiohttp==2.3.10
,python3.5
,Django==2.1.3
我的目录结构如下:
├─project1
├─app1
├─management
├─commands
└─pull_campaign_list_every_15m.py
我的主要代码:
class Command(BaseCommand):
help = "pull campaign data"
def handle(self, *args, **options):
# get related data here
task_list = []
for account_info in account_data_list:
#...
campaign_list = [campaign_list_data,...,] # get from http request
task_list.extend([
asyncio.ensure_future(
_handle_campaign_list(related_param)) for campaign in
campaign_list if campaign_list
])
loop = asyncio.get_event_loop()
try:
loop.run_until_complete(asyncio.wait(task_list))
except Exception as e:
info_logger.info(e)
finally:
loop.close()
async def _handle_campaign_list(realated_param):
# do something here batch handle list data
try:
async with aiohttp.ClientSession() as session:
async with session.get(url) as response:
result = await response.text()
temp_data = json.loads(result)
# save data here using Django ORM
except aiohttp.client_exceptions.ClientConnectorError:
info_logger.info("bad request connect error")
except asyncio.TimeoutError:
info_logger.info("server timeout")
当我调用python manage.py pull_campaign_list_every_15m
之类的命令时,出现如下错误:
Traceback (most recent call last):
File "manage.py", line 15, in <module>
execute_from_command_line(sys.argv)
File "/home/.virtualenvs/project1/lib/python3.5/site-packages/django/core/management/__init__.py", line 381, in execute_from_command_line
utility.execute()
File "/home/.virtualenvs/project1/lib/python3.5/site-packages/django/core/management/__init__.py", line 375, in execute
self.fetch_command(subcommand).run_from_argv(self.argv)
File "/home/.virtualenvs/project1/lib/python3.5/site-packages/django/core/management/base.py", line 316, in run_from_argv
self.execute(*args, **cmd_options)
File "/home/.virtualenvs/project1/lib/python3.5/site-packages/django/core/management/base.py", line 353, in execute
output = self.handle(*args, **options)
File "/home/project1/app1/management/commands/pull_campaign_list_every_15m.py", line 77, in handle
campaign_list if campaign_list
File "/home/project1/app1/management/commands/pull_campaign_list_every_15m.py", line 77, in <listcomp>
campaign_list if campaign_list
File "/usr/local/lib/python3.5/asyncio/tasks.py", line 547, in ensure_future
task = loop.create_task(coro_or_future)
File "/usr/local/lib/python3.5/asyncio/base_events.py", line 259, in create_task
self._check_closed()
File "/usr/local/lib/python3.5/asyncio/base_events.py", line 334, in _check_closed
raise RuntimeError('Event loop is closed')
RuntimeError: Event loop is closed
sys:1: RuntimeWarning: coroutine '_handle_campaign_list' was never awaited
为什么在这种情况下事件循环关闭?任何帮助或见识将不胜感激,非常感谢。