I am creating a connection instance before the start of the application
# app.py
mongodb_conn = pymongo.Connection(host=host, port=int(port), safe=True)
print(mongodb_conn) # Connection('127.0.0.1', 27017)
...
bottle.run(...)
But, then in my requests, when I try to access this connection from other modules, it errs saying that mongodb_conn is None
# user.py
from app import mongodb_conn
...
db = mongodb_conn['somedb'] # TypeError: 'NoneType' object is not subscriptable
Can someone explain what’s going on?
Ok, I have been able to solve the problem. It was related to some discrepancies in module loading orders.
But, it is perfectly alright to cache ONE connection instance and then use it for the entire lifetime of the application. And this is true even for threaded applications.