From 7f8c5dcddc677f012c11f44f2d30502bc05c94a6 Mon Sep 17 00:00:00 2001 From: radluz <48119760+radluz@users.noreply.github.com> Date: Mon, 17 Feb 2025 10:06:10 +0000 Subject: [PATCH] fix: update asyncio event loop policy on Windows (#251) * fix: update asyncio event loop policy on Windows * Use `platform.system` instead of `sys.platform` --------- Co-authored-by: Waket Zheng --- aerich/__init__.py | 24 ++++++++++++++++++++++++ 1 file changed, 24 insertions(+) diff --git a/aerich/__init__.py b/aerich/__init__.py index 74f840c..908c4f0 100644 --- a/aerich/__init__.py +++ b/aerich/__init__.py @@ -1,6 +1,7 @@ from __future__ import annotations import os +import platform from pathlib import Path from typing import TYPE_CHECKING @@ -26,6 +27,29 @@ if TYPE_CHECKING: from aerich.inspectdb import Inspect +def _init_asyncio_patch(): + """ + Select compatible event loop for psycopg3. + + As of Python 3.8+, the default event loop on Windows is `proactor`, + however psycopg3 requires the old default "selector" event loop. + See https://www.psycopg.org/psycopg3/docs/advanced/async.html + """ + if platform.system() == "Windows": + try: + from asyncio import WindowsSelectorEventLoopPolicy + except ImportError: + pass # Can't assign a policy which doesn't exist. + else: + from asyncio import get_event_loop_policy, set_event_loop_policy + + if not isinstance(get_event_loop_policy(), WindowsSelectorEventLoopPolicy): + set_event_loop_policy(WindowsSelectorEventLoopPolicy()) + + +_init_asyncio_patch() + + class Command: def __init__( self,