我有一个可以返回MongoDB数据库连接处理程序的函数。我有其他一些需要调用该数据库的函数,所以我想把连接处理程序放到一个函数中,这样我不必在每个函数中定义它。
看起来这样做没问题吗?我的问题是,如果无法连接到数据库服务器,它将同时打印两条消息"Could not connect to server"和"No hosts found"。我该如何只打印"Could not connect to the server"呢?
看起来这样做没问题吗?我的问题是,如果无法连接到数据库服务器,它将同时打印两条消息"Could not connect to server"和"No hosts found"。我该如何只打印"Could not connect to the server"呢?
def mongodb_conn():
try:
conn = pymongo.MongoClient()
except pymongo.errors.ConnectionFailure, e:
print "Could not connect to server: %s" % e
return conn
def get_hosts()
try:
conn = mongodb_conn()
mongodb = conn.dbname.collection
b = []
hosts_obj = mongodb.find({'_id': 'PR'})
for x in hosts_obj:
print x
except:
print "No hosts found"
get_hosts()
mongodb_conn
中可能会出现错误:如果发生异常,conn
将永远未被定义! - ForceBruexcept: pass
- ρss