Example how to use Python Sanic and Async MongoDB Driver
- Install python sanic
$ pip install sanic
- Install Motor (Asynchronous Python driver for MongoDB)
$ pip install motor
- Create conection pool
import urllib.parse
import motor.motor_asyncio as async_motor
@app.listener('before_server_start')
async def register_db(app, loop):
# Create a database connection pool
connection_uri = "mongodb://{username}:{password}@{host}:{port}/".format(
username="foo", password=urllib.parse.quote("bar"),
host="localhost", port=27017
)
database_name = "foobar"
app.config['db'] = async_motor.AsyncIOMotorClient(
connection_uri,
# in milliseconds
maxIdleTimeMS=10000,
# minimal pool size
minPoolSize=10,
# maximal pool size
maxPoolSize=50,
# connection timeout in miliseconds
connectTimeoutMS=10000,
# boolean
retryWrites=True,
# wait queue in miliseconds
waitQueueTimeoutMS=10000,
# in miliseconds
serverSelectionTimeoutMS=10000
)[database_name]
- To see detail code you can check
main.py
- Happy coding :)