@@ -109,7 +109,11 @@ def __init__(self, database=None, *, loop=None):
109
109
110
110
self .loop = loop or asyncio .get_event_loop ()
111
111
self .database = database or self .database
112
- self .database .loop = self .loop
112
+ attach_callback = getattr (self .database , 'attach_callback' , None )
113
+ if attach_callback :
114
+ attach_callback (lambda db : db .set_event_loop (self .loop ))
115
+ else :
116
+ self .database .set_event_loop (self .loop )
113
117
114
118
@property
115
119
def is_connected (self ):
@@ -819,6 +823,22 @@ class AsyncDatabase:
819
823
_async_wait = None # connection waiter
820
824
_task_data = None # task context data
821
825
826
+ def set_event_loop (self , loop ):
827
+ """Set event loop for the database. Usually, you don't need to
828
+ call this directly. It's called from `Manager.connect()` or
829
+ `.connect_async()` methods.
830
+ """
831
+ # These checks are not very pythonic, but I believe it's OK to be
832
+ # a little paranoid about mismatching of asyncio event loops,
833
+ # because such errors won't show clear traceback and could be
834
+ # tricky to debug.
835
+ loop = loop or asyncio .get_event_loop ()
836
+ if not self .loop :
837
+ self .loop = loop
838
+ elif self .loop != loop :
839
+ raise RuntimeError ("Error, the event loop is already set before. "
840
+ "Make sure you're using the same event loop!" )
841
+
822
842
@asyncio .coroutine
823
843
def connect_async (self , loop = None , timeout = None ):
824
844
"""Set up async connection on specified event loop or
@@ -833,7 +853,7 @@ def connect_async(self, loop=None, timeout=None):
833
853
elif self ._async_wait :
834
854
yield from self ._async_wait
835
855
else :
836
- self .loop = loop or asyncio . get_event_loop ( )
856
+ self .set_event_loop ( loop )
837
857
self ._async_wait = asyncio .Future (loop = self .loop )
838
858
839
859
conn = self ._async_conn_cls (
0 commit comments