简体   繁体   中英

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?

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM