PyMongo insert_one 异常/错误处理

我正在尝试确保我已设置错误处理。我不确定我是否使用了 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()


慕丝7291255
浏览 98回答 1
1回答

慕运维8079593

我没有看到任何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 Falsedef 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()
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python