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