On the Execution Order of Simultaneous Listening Events

app.listener('before_server_start') Why is it executed last?

# app/server.py a part...
def create_app():
    app = Sanic('app')

    @app.listener("before_server_start")
    async def test1(app, loop):
        print(''first...")

    print("second...")
    
    return app

Running results:
second…
first…

I use umongo orm. I will add database connection information in app.listener(“before_server_start”)

# app/server.py. a part..
@app.listener('before_server_start')
    async def mongodb_configure(app_inner):
        client = AsyncIOMotorClient(app_inner.config.get('MONGODB_URI'))
        instance = MotorAsyncIOInstance(client.run)
        app.ctx.db = instance

Then add a decorator to the model

# app/model/user.py a part ...
@app.ctx.db.register
class User(Document):
    _id = fields.ObjectIdField()
    name = fields.StringField(default='', max_length=50, description='The name of the user')
    password = fields.StringField(default='', max_length=50, description='The name of the user')

Back to the beginning, If listener executed last, this error will be reported app.ctx.db undefault error
May I ask how to solve it, online, etc. Thank you very much!

create_app is executed when the application is started and the instance is loaded into memory. Therefore, second is printed. Only after there is an application can the server process be initiated. One of the steps is to run the before_server_start listener.

Why do you think it should be the other way around?

It has been solved, refer to this library( sanic-mongodb-extension), the previous code does have problems with the newer umongo version, but it was updated yesterday :stuck_out_tongue_winking_eye: