import pymongo
import sys
MONGO_USER = "ID"
MONGO_PASS = "Password"
def user_input():
MONGO_HOST = 'mongodb://000.000.000.000' # server address
MONGO_DB = 'databse' # database of interest in the server
connection = pymongo.MongoClient(MONGO_HOST) # connects to the remote database server
db = connection[MONGO_DB] # specifies the database we want to use
try:
log_in = db.authenticate(MONGO_USER, MONGO_PASS)
except:
log_in = False # returns False if authentication fails
finally:
return log_in,db
因此,我想针对不同类型的身份验证错误提出不同的异常。我想引发指定服务器未打开的异常,以及用户输入错误ID或密码的异常。所以,像这样:
try:
log_in = db.authenticate(MONGO_USER, MONGO_PASS)
except wrong_ID_or_Password:
log_in = False
---prompt the user to try again
except something_internally_wrong_with_server:
log_in = False
print("server is wrong")
sys.exit(1)
每种情况下我应该使用哪些代码?我需要专门为Pymongo工作的代码。我已经看过Pymongo的文档,如
except pymongo.errors.InvalidName:
do something
但不起作用。
这是我找到的文档: http://api.mongodb.com/python/current/api/pymongo/errors.html
我已经尝试过InvalidName:来自该文档的异常,但是当我尝试输入错误的ID时,它并没有转到该异常处理程序。所以,当我使用:
MONGO_USER = "wrong_ID"
....
except pymongo.errors.InvalidName:
print("incorrect ID")
它应该转到InvalidName:异常处理程序,并打印"不正确的ID",但它没有