from sqlalchemy import create_engine
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import sessionmaker
@app.listener('before_server_start')
async def before_server_start(app, loop):
# database config
app.engine = create_engine(app.config['SQLALCHEMY_DATABASE_URI'], echo=app.config['SQLALCHEMY_TRACK_MODIFICATIONS'])
app.Base = declarative_base(bind=app.engine)
Session = sessionmaker(bind=app.engine)
app.db_session = Session()
app.Base.metadata.create_all()
这是我的一段代码,listener('before_server_start') 在服务启动前运行, 我把 sqlalchemy 所必须的几个对象和类变成 app ( Sanic 的对象)的属性后, 当我想要在 models 中想要类似这样定义的时候:
class User(app.Base)
却报错。
也就是说,模块加载的时间在 app.listener('before_server_start')运行之前。
不知道有用 Sanic+sqlalchemy 你们怎么做的?

文档给的一个 example。