我是Sanic的新手,我正试图让它与Motor合作。我确实设法让所有东西都在一个文件中工作,但是,当我在项目结构中尝试时,我遇到了以下问题。
[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 <Task pending coro=<Sanic.handle_request() running at
/usr/local/lib/python3.6/site-packages/sanic/app.py:556> created at
/usr/local/lib/python3.6/site-packages/sanic/server.py:299> got Future
<Future pending cb=[run_on_executor.<locals>._call_check_cancel() at
/usr/local/lib/python3.6/site-
packages/motor/frameworks/asyncio/__init__.py:85]> attached to a different
loop
我做了一些研究,正如Sanic的GitHub页面所提到的那样,尝试了之前的服务器块&#39;数据库设置部分。但这不适用于我的项目结构。
我的项目结构类似于:
以下是我的代码。我已经在一个更简单的结构中重新创建了这个问题而没有失去本质。
的src / MyPackage的/型号/ user.py
class User(object):
def __init__(self, first, last):
self.first = first
self.last = last
的src / MyPackage的/ UC / user_uc.py
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
的src / DAO / motor_connection.py
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
的src / DAO / user_DAO.py
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
的src / MyPackage的/ REST / user_REST.py
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)
最后是主程序......
的src / MyPackage的/ main.py
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)
我没有包含任何子包的 init .py文件。我在这些文件中唯一做的就是将类带到子包级别。
从我能够弄清楚的,当导入User_Rest类时,似乎在main.py中导入了导入User_DAO类的User_UC类,而User_DAO类又导入了Motor_Connection类 - 这就是混乱的地方发生。这会创建一个单独的事件循环,Sanic不会共享它。
因此,如果我的理解是正确的,那么所有链接的导入类都使用一个事件循环,而Sanic使用另一个事件循环。我知道我们不能有2个事件循环,但我无法弄清楚需要做些什么才能解决这个问题。
请帮忙。提前谢谢。
答案 0 :(得分:5)
确定。问题得到解决。我不得不使用全局变量来解决它。请在下面找到修改后的代码以供参考。
main.py
from sanic import Sanic
from DAO import Motor_Connection
from REST import User_REST
import commons
app = Sanic()
@app.listener('before_server_start')
def init(sanic, loop):
commons.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)
commons.globals.py
db = None
user_DAO.py
import commons
class User_DAO(object):
async def register_user(self, serialized_user):
result = await commons.db.users.insert_one(serialized_user)
return result.inserted_id
说明:虽然电机连接类是单例并且返回了相同的实例,因为它在导入过程中被初始化,但是Sanic无法获得事件循环的句柄。首先必须初始化Sanic以便能够处理事件循环。
通过使用全局变量并在before_server_start块中初始化它,Sanic获取句柄。现在,当您在DAO类中使用相同的变量时,您可以访问Sanic的事件循环。