treecoder
treecoder

Reputation: 45131

Why can I not share a pymongo connection instance in my bottlepy application

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?

Upvotes: 3

Views: 476

Answers (2)

jdi
jdi

Reputation: 92617

I know you already mentioned in your answer that you solved it because of a module order issue, but I wanted to include an expanded answer.

Without seeing more of your code, I am assuming you are setting up some circular importing, where the connection is defined in your app.py, which probably also imports your user.py, but then your user.py imports app.py for the connection objects. mongodb_conn is most likely unassociated at that point.

What I would recommend is that you create a 3rd module called db.py. Create either a global variable connection in there, or, create a simple singleton class that always returns the same connection, or, a simple function like getConnection() that always returns the global connection. This way, you won't have circular imports and any other module can import db

Upvotes: 1

treecoder
treecoder

Reputation: 45131

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.

Upvotes: 1

Related Questions