Skip to content

Commit

Permalink
Merge pull request #2 from sampingantech/bugfix/use-thread-instead-ne…
Browse files Browse the repository at this point in the history
…st-asyncio

lib: Use thread instead nest_asyncio
  • Loading branch information
isasetiawan authored Apr 23, 2021
2 parents ab77631 + a72f7d2 commit a18b8e4
Show file tree
Hide file tree
Showing 2 changed files with 17 additions and 5 deletions.
19 changes: 16 additions & 3 deletions casbin_databases_adapter/utils.py
Original file line number Diff line number Diff line change
@@ -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):
Expand Down Expand Up @@ -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

Expand Down
3 changes: 1 addition & 2 deletions requirements.txt
Original file line number Diff line number Diff line change
@@ -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

0 comments on commit a18b8e4

Please sign in to comment.