Sanic: Antipattern in Motor example

Created on 3 May 2017  路  2Comments  路  Source: sanic-org/sanic

Hi, I would have filed a PR to adjust this but I wasn't sure on what the correct structure would be in Sanic.

The current example for Motor creates a MotorClient upon every request to the /objects endpoint. A Motor client instance creates a connection pool for requests, so should be created once at app startup and reused through the apps lifetime. Creating client for every request is probably ok for an example app but isn't representative of how a real app should work.

I wanted to file a PR with a fix for this where the Motor client is created up front in the global scope, but ran into the already-discussed issue whereby Sanic uses a different event loop than the Motor client (presumably because Sanic's loop is created inside app.run).

1) How should this example look if it were restructured to only create the Motor client once?
2) Would it be possible to add more documentation about ensuring other libraries always use the same event loop? The solution for this wasn't clear from the existing docs.

I'm happy to file PRs for either/both of those if you could clarify best practise in this issue. Thanks!

Most helpful comment

Sow with asyncio in Python 3.6 any call made using get_event_loop while an event loop is currently running will automatically default to the currently running event loop. So you can use things like the MotorClient as is.

If you would like to create one instance of MotorClient and utilize it across all of your request handlers I'd suggest you look at something similar to: https://github.com/channelcat/sanic/blob/master/examples/sanic_asyncpg_example.py#L31

Wherein you create your client in the before_server_start event handler and utilize it within your request handlers.

All 2 comments

Sow with asyncio in Python 3.6 any call made using get_event_loop while an event loop is currently running will automatically default to the currently running event loop. So you can use things like the MotorClient as is.

If you would like to create one instance of MotorClient and utilize it across all of your request handlers I'd suggest you look at something similar to: https://github.com/channelcat/sanic/blob/master/examples/sanic_asyncpg_example.py#L31

Wherein you create your client in the before_server_start event handler and utilize it within your request handlers.

Awesome, that's really helpful, thanks for the explanation :) I'll close this ticket and file a PR for the motor example shortly.

Was this page helpful?
0 / 5 - 0 ratings

Related issues

geekpy picture geekpy  路  4Comments

graingert picture graingert  路  3Comments

davidtgq picture davidtgq  路  3Comments

sirex picture sirex  路  4Comments

ZeeRoc picture ZeeRoc  路  3Comments