clifgray
clifgray

Reputation: 4419

Where to put client and db connection in python file

So I am building a mongo database class that will be provide access to inserting documents to the insertion service and provide access for viewing documents via a querying service. Right now I have the following for my database.py class:

import pymongo 

client = pymongo.MongoClient('mongodb://localhost:27017/')
db_connection = client['my_database']

class DB_Object(object):

    """ A class providing structure and access to the Database """

    def add_document(self, json_obj):
        coll = db_connection["some collection"]
        document = {
            "name" : "imma name",
            "raw value" : 777,
            "converted value" : 333
        }
        coll.insert(document)

    def query_response(self, query):
            """query logic here"""

If I want concurrent queries and inserts with this class being called by multiple services is this the correct location for the lines:

client = pymongo.MongoClient('mongodb://localhost:27017/')
db_connection = client['my_database']

And is this a standard way to provide access?

Upvotes: 0

Views: 1043

Answers (1)

A. Jesse Jiryu Davis
A. Jesse Jiryu Davis

Reputation: 24007

Your code is correct. You should continue to use the same MongoClient instance for all operations in your application, this will ensure that all operations share the same connection pool and use as few connections as possible--this will maximize your efficiency. MongoClient is thread-safe so this will work even if you have concurrent operations on multiple threads.

Upvotes: 1

Related Questions