[Python / Error] aiohttpのRuntimeError: no running event loopエラー

[Python / Error] aiohttpのRuntimeError: no running event loopエラー

概要

  • aiohttpパッケージからレスポンスを取得する処理を作成中に
    『RuntimeError: no running event loop』エラーが発生しました。
  • 原因はaiohttpのレスポンスの取得処理は非同期対応が必要だからでした。
  • それでaiohttpのレスポンスの取得処理の非同期の対応内容を作成しました。
# ソースコード
import aiohttp

def get_response_test(req_url : str) :
  with aiohttp.ClientSession(connector=aiohttp.TCPConnector(ssl=True)) as session:
    with session.get(req_url) as response :
      print(response.status)

if __name__ == '__main__':
  get_response_test("https://www.crob-diary.net/")
# エラー内容
Exception has occurred: RuntimeError
no running event loop

with aiohttp.ClientSession(connector=aiohttp.TCPConnector(ssl=True)) as session:
RuntimeError: no running event loop

開発環境

  • Python 3.12.5
  • aiohttp 3.10.3

参考

対応

main処理を非同期対応にする

  1. 非同期処理のためにasyncioパッケージをimportします。
  2. 非同期で実行する処理をasyncio.run()で囲みます。
# ソースコード
import aiohttp
import asyncio  # 1.非同期処理のためにasyncioパッケージをimportします。

def get_response_test(req_url : str) :
  with aiohttp.ClientSession(connector=aiohttp.TCPConnector(ssl=True)) as session:
    with session.get(req_url) as response :
      print(response.status)

if __name__ == '__main__':
  # 2.非同期で実行する処理をasyncio.run()で囲みます。
  asyncio.run(get_response_test("https://www.crob-diary.net/"))

処理を行うメソッドを非同期対応にする

  • 『asyncio.run()』で囲んだメソッドの定義にasyncを追記します。
  • ここでは次の3カ所に追記しました。
    1. def get_response_testの前のメソッドの定義
    2. with aiohttp.ClientSession(connector=aiohttp.TCPConnector(ssl=True)) as session: の前
    3. with session.get(req_url) as response : の前
  • 正常に実行されるとresponseコード200 (正常)が出力されます。
# ソースコード
# 1.メソッド定義の前にasyncを追記します。
async def get_response_test(req_url : str) :
  # 2.「with aiohttp.ClientSession」の前にasyncを追記します。
  async with aiohttp.ClientSession(connector=aiohttp.TCPConnector(ssl=True)) as session:
    # 3.「with session.get」の前にasyncを追記します。
    async with session.get(req_url) as response :
      print(response.status)

if __name__ == '__main__':
  asyncio.run(get_response_test("https://www.crob-diary.net/"))

実行結果 :

200