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()