PyMongo insert_one exception/error handling

Question:

I am trying to make sure I have set up error handling. I am not sure if I am using try, except, and return correctly.

The desired output is True or False
True if the document is inserted successfully, False if not. Have I done it correctly? My concern that is that it will always return true? Not exactly sure how try/except works.Thank you.

import json
import pymongo
from bson import json_util
from pymongo import MongoClient
from pymongo import errors

connection = MongoClient('localhost', 27017)
db = connection['city']
collection = db['inspections']

def insert_document(documentToInsert):
    try:
      collection.insert_one(documentToInsert)
      return True
    except WriteConcernError as wce:
      print(wce)
      return False
    except WriteError as we:
      print(we)
      return False


def main():
    document = { 
      "id" : "11111-2019-ENFO",
      "certificate_number" : 9278806,
      "business_name" : "TAXOLOGY",
      "date" : "Feb 20 2015",
      "result" : "No Violation Issued",
      "sector" : "Accounting - 111",
      "address" :
      {
        "city" : "MISSION HILLS",
        "zip" : 91401,
        "street" : "Sepulveda",
        "number" : 1809
      }
    }

    print(insert_document(document))

main()
Asked By: Etra

||

Answers:

I don’t see any write_concern being passed-in as an option to your writes, I would assume you might not see WriteConcernError. Check this : pymongo.write_concern.WriteConcern for examples on how to set WriteConcern . Also those error checks are only needed if you wanted to execute certain functionality if a certain type of an error occurred, As all you need is to return True / False, then you can remove all those error checks :

Code :

connection = MongoClient('localhost', 27017)
db = connection['city']
collection = db['inspections']


def insert_document(documentToInsert):
    try:
        collection.insert_one(documentToInsert)
        return True
    except Exception as e:
        print("An exception occurred ::", e)
        return False


def main():
    document = {
        "id": "11111-2019-ENFO",
        "certificate_number": 9278806,
        "business_name": "TAXOLOGY",
        "date": "Feb 20 2015",
        "result": "No Violation Issued",
        "sector": "Accounting - 111",
        "address":
        {
            "city": "MISSION HILLS",
            "zip": 91401,
            "street": "Sepulveda",
            "number": 1809
        }
    }

    print(insert_document(document))


main()

Your implementation of error handling using try/except is correct.

In your code, if the collection.insert_one() method runs successfully, the try block will be executed, and it will return True. However, if an exception occurs during the execution of the insert_one() method, the exception will be caught in the except block. In this case, the function will return False after printing the error message.

In the except block, you have used two types of exceptions to handle errors:

WriteConcernError: It is raised when a write concern error occurs during an operation.
WriteError: It is raised when a write operation encounters an error.
Both of these exceptions are part of the pymongo.errors module, which you have imported at the beginning of your code.

So, in summary, your implementation is correct, and it will return True if the document is inserted successfully, and False if an error occurs during the insertion.

Answered By: pugs_are_death
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.