From a72f7d2f77304d4cdb5261765142ef4719725620 Mon Sep 17 00:00:00 2001 From: Sakti Dwi Cahyono Date: Fri, 23 Apr 2021 13:54:45 +0700 Subject: [PATCH] lib: Use thread instead nest_asyncio Use thread to run nested event loop, since nest_asyncio patch doesn't work on uvloop. --- casbin_databases_adapter/utils.py | 19 ++++++++++++++++--- requirements.txt | 3 +-- 2 files changed, 17 insertions(+), 5 deletions(-) diff --git a/casbin_databases_adapter/utils.py b/casbin_databases_adapter/utils.py index aeeb8be..0aa5c1d 100644 --- a/casbin_databases_adapter/utils.py +++ b/casbin_databases_adapter/utils.py @@ -1,9 +1,19 @@ import asyncio import functools +import threading from asyncio import Task from typing import Callable, Coroutine -import nest_asyncio + +class RunThread(threading.Thread): + def __init__(self, func, args, kwargs): + self.func = func + self.args = args + self.kwargs = kwargs + super().__init__() + + def run(self): + self.result = asyncio.run(self.func(*self.args, **self.kwargs)) def to_sync(as_task: bool = True): @@ -31,8 +41,11 @@ def func_wrapper(*args, **kwargs): _to_task(func(*args, **kwargs), as_task, loop) ) else: - nest_asyncio.apply(loop) - return asyncio.run(_to_task(func(*args, **kwargs), as_task, loop)) + # handle nested event loop with thread + thread = RunThread(func, args, kwargs) + thread.start() + thread.join() + return thread.result return func_wrapper diff --git a/requirements.txt b/requirements.txt index a7aba2d..5a930ba 100644 --- a/requirements.txt +++ b/requirements.txt @@ -1,4 +1,3 @@ casbin>=0.8.1 SQLAlchemy>=1.2.18 -databases>=0.2.6 -nest-asyncio==1.5.1 +databases>=0.2.6 \ No newline at end of file