Skip to content

Commit a18b8e4

Browse files
authored
Merge pull request #2 from sampingantech/bugfix/use-thread-instead-nest-asyncio
lib: Use thread instead nest_asyncio
2 parents ab77631 + a72f7d2 commit a18b8e4

2 files changed

Lines changed: 17 additions & 5 deletions

File tree

casbin_databases_adapter/utils.py

Lines changed: 16 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,9 +1,19 @@
11
import asyncio
22
import functools
3+
import threading
34
from asyncio import Task
45
from typing import Callable, Coroutine
56

6-
import nest_asyncio
7+
8+
class RunThread(threading.Thread):
9+
def __init__(self, func, args, kwargs):
10+
self.func = func
11+
self.args = args
12+
self.kwargs = kwargs
13+
super().__init__()
14+
15+
def run(self):
16+
self.result = asyncio.run(self.func(*self.args, **self.kwargs))
717

818

919
def to_sync(as_task: bool = True):
@@ -31,8 +41,11 @@ def func_wrapper(*args, **kwargs):
3141
_to_task(func(*args, **kwargs), as_task, loop)
3242
)
3343
else:
34-
nest_asyncio.apply(loop)
35-
return asyncio.run(_to_task(func(*args, **kwargs), as_task, loop))
44+
# handle nested event loop with thread
45+
thread = RunThread(func, args, kwargs)
46+
thread.start()
47+
thread.join()
48+
return thread.result
3649

3750
return func_wrapper
3851

requirements.txt

Lines changed: 1 addition & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,3 @@
11
casbin>=0.8.1
22
SQLAlchemy>=1.2.18
3-
databases>=0.2.6
4-
nest-asyncio==1.5.1
3+
databases>=0.2.6

0 commit comments

Comments
 (0)