mahboi
mahboi

Reputation: 36

What is the proper way to share MongoClient using flask_pymongo in larger application?

I'm building a REST API using flask_restful and I am currently looking into connecting it to a MongoDB database. I've been looking a bit on flask_pymongo and if I've understood correctly you create an object representing the connection and use this object for your queries.

In the examples I've seen one single file is used and the object is global. In a larger project I will need to share this object in some way. Will I have to make this object global or is there any better way to handle it?

Upvotes: 0

Views: 396

Answers (1)

nickmilon
nickmilon

Reputation: 1372

For a single file (module) you instantiate the connection object somewhere in the beginning of your file

con = MongoClient(....)

then you can use it in your end-point definitions no need to define it as global since you are not going to modify its properties in any way.

def endpoint1(....)
    .....
    result = con['dbname']['collectionname'].find({...})

def endpoint2(....)
    .....
    result = con['dbname']['collectionname'].find({...})

If you need it in an other module just import it.

from yourmodule import con

Upvotes: 1

Related Questions