PyMongo insert_one异常/错误处理

时间:2020-02-04 22:20:27

标签: python mongodb pymongo

我正在尝试确保已设置错误处理。我不确定是否正在使用try(除外)并正确返回。

所需的输出为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()

1 个答案:

答案 0 :(得分:2)

我看不到有任何write_concern作为写操作的选项被传递,我假设您可能看不到WriteConcernError。检查以下内容:pymongo.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()