mongodb PyMongo insert_one异常/错误处理

wqsoz72f  于 2023-02-21  发布在  Go
关注(0)|答案(1)|浏览(123)

我正在尝试确定我已经设置了错误处理。我不确定我是否正确地使用了try、except和return。
所需的输出为True或False如果文档插入成功,则为True;否则为False。我的操作是否正确?我担心的是它总是返回True?不完全确定try/except如何工作。谢谢。

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

idfiyjo81#

我没有看到任何write_concern作为选项传入到您的write中,我假设您可能没有看到WriteConcernErrorpymongo.write_concern.WriteConcern,以获取如何设置WriteConcern的示例。此外,只有在发生特定类型的错误时,您希望执行特定功能时才需要这些错误检查。由于您只需要返回True/False,因此您可以删除所有这些错误检查:

    • 代码:**
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()

相关问题