title: Sanic and Motor use different event loops
body: <p>I am new to Sanic and I am trying to get it to work with Motor. I did manage to get everything to work in a single file, however, when I try it out within my project structure, I am running into the below issues.</p>
  
  <pre><code>[2018-02-28 17:26:58 +0530] [3720] [ERROR] Traceback (most recent call 
  last):
  File "/usr/local/lib/python3.6/site-packages/sanic/app.py", line 556, in 
  handle_request
  response = await response
  File "/usr/src/Python-3.6.4/Lib/asyncio/coroutines.py", line 129, in throw
  return self.gen.throw(type, value, traceback)
  File "/home/msambare/Documents/Projects/Snippets/Sanic-Motor-
  Issue/IAC/src/MyPackgae/REST/user_REST.py", line 42, in post
  request.json['last']
  File "/usr/src/Python-3.6.4/Lib/asyncio/coroutines.py", line 129, in throw
  return self.gen.throw(type, value, traceback)
  File "/home/msambare/Documents/Projects/Snippets/Sanic-Motor-
  Issue/IAC/src/MyPackgae/DAO/user_DAO.py", line 40, in register_user
  result = await db.users.insert_one(serialized_user)
  RuntimeError: Task &lt;Task pending coro=&lt;Sanic.handle_request() running at 
  /usr/local/lib/python3.6/site-packages/sanic/app.py:556&gt; created at 
  /usr/local/lib/python3.6/site-packages/sanic/server.py:299&gt; got Future 
  &lt;Future pending cb=[run_on_executor.&lt;locals&gt;._call_check_cancel() at 
  /usr/local/lib/python3.6/site-
  packages/motor/frameworks/asyncio/__init__.py:85]&gt; attached to a different 
  loop
  </code></pre>
  
  <p>I did some research and as mentioned on the GitHub pages of Sanic, tried the 'before-server-block' section for db setup. That works in a single file, however, not in my project structure.</p>
  
  <p>My project structure looks something like:</p>
  
  <p><a href="https://i.stack.imgur.com/lq7q0.jpg" rel="noreferrer">Project Structure</a></p>
  
  <p>Below is my code. I have recreated the issue in a simpler structure without losing the essence.</p>
  
  <p><em>src/MyPackage/Model/user.py</em></p>
  
  <pre><code>class User(object):
  def __init__(self, first, last):
      self.first = first
      self.last = last
  </code></pre>
  
  <p><em>src/MyPackage/UC/user_uc.py</em></p>
  
  <pre><code>from Model import User
  from DAO import User_DAO
  
  
  class User_UC(object):
      def __init__(self):
          self._user = None
  
      def create_user(self, first, last):
          self._user = User(first, last)
          ud = User_DAO()
          id = ud.register_user(
              {
                  'first': first,
                  'last': last
              }
          )
          return id
  </code></pre>
  
  <p><em>src/DAO/motor_connection.py</em></p>
  
  <pre><code>import uvloop
  import asyncio
  import motor.motor_asyncio
  
  
  asyncio.set_event_loop_policy(uvloop.EventLoopPolicy())
  
  
  class Motor_Connection(object):
      """ Provides a MongoDB connection and sets the DB to be used.
  
      The class implements the Singleton pattern.
      """
  
      __instance = None
  
      def __new__(cls):
          if Motor_Connection.__instance is None:
              Motor_Connection.__instance = object.__new__(cls)
  
              Motor_Connection.__instance.client = \
                  motor.motor_asyncio.AsyncIOMotorClient(
                      'localhost',
                      27017,
                      io_loop=asyncio.get_event_loop()
                  )
  
              Motor_Connection.__instance.db = \
                  Motor_Connection.__instance.client.test_database
  
          return Motor_Connection.__instance.db
  </code></pre>
  
  <p><em>src/DAO/user_DAO.py</em></p>
  
  <pre><code>from DAO import Motor_Connection
  
  
  db = Motor_Connection()
  
  
  class User_DAO(object):
      async def register_user(self, serialized_user):
          result = await db.users.insert_one(serialized_user)
          return result.inserted_id
  </code></pre>
  
  <p><em>src/MyPackage/REST/user_REST.py</em></p>
  
  <pre><code>from sanic.views import HTTPMethodView
  from sanic.response import text
  from UC import User_UC
  
  
  class User_REST(HTTPMethodView):
      async def post(self, request):
          user_uc = User_UC()
          id = await user_uc.create_user(
              request.json['first'],
              request.json['last']
          )
          return text(id)
  </code></pre>
  
  <p>and finally the main program...</p>
  
  <p><em>src/MyPackage/main.py</em></p>
  
  <pre><code>from sanic import Sanic
  from DAO import Motor_Connection
  from REST import User_REST
  
  
  app = Sanic()
  
  
  @app.listener('before_server_start')
  def init(sanic, loop):
      global db
      db = Motor_Connection()
  
  
  app.add_route(User_REST.as_view(), '/')
  
  
  if __name__ == "__main__":
      app.run(host="0.0.0.0", port=8000, workers=3, debug=True)
  </code></pre>
  
  <p>I have not included the <strong>init</strong>.py files of any of the sub-packages. The only thing that I have done in those files is bringing the classes to the sub-package level.</p>
  
  <p>From what I have been able to figure out, it seems in main.py when the User_Rest class is imported which in turn imports the User_UC class which imports the User_DAO class which in turn imports the Motor_Connection class - this is where the mess happens. This creates a separate event loop which is not shared by Sanic.</p>
  
  <p>So, if my understanding is correct, all the chained imported classes use one event loop and Sanic uses another event loop. I know we cannot have 2 event loops but I am unable to figure out what needs to be done to sort this out.</p>
  
  <p>Please help. Thanks in advance.</p>