本文整理汇总了Python中pymongo.errors.ConnectionFailure方法的典型用法代码示例。如果您正苦于以下问题:Python errors.ConnectionFailure方法的具体用法?Python errors.ConnectionFailure怎么用?Python errors.ConnectionFailure使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类pymongo.errors
的用法示例。
在下文中一共展示了errors.ConnectionFailure方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: connect
# 需要导入模块: from pymongo import errors [as 别名]
# 或者: from pymongo.errors import ConnectionFailure [as 别名]
def connect(self):
"""Connect to Mongo and return a new (connected) socket. Note that the
pool does not keep a reference to the socket -- you must call
return_socket() when you're done with it.
"""
sock = self.create_connection()
hostname = self.pair[0]
if self.use_ssl:
try:
sock = ssl.wrap_socket(sock,
certfile=self.ssl_certfile,
keyfile=self.ssl_keyfile,
ca_certs=self.ssl_ca_certs,
cert_reqs=self.ssl_cert_reqs)
if self.ssl_cert_reqs:
match_hostname(sock.getpeercert(), hostname)
except ssl.SSLError:
sock.close()
raise ConnectionFailure("SSL handshake failed. MongoDB may "
"not be configured with SSL support.")
sock.settimeout(self.net_timeout)
return SocketInfo(sock, self.pool_id, hostname)
示例2: _reset_on_error
# 需要导入模块: from pymongo import errors [as 别名]
# 或者: from pymongo.errors import ConnectionFailure [as 别名]
def _reset_on_error(self, server, func, *args, **kwargs):
"""Execute an operation. Reset the server on network error.
Returns fn()'s return value on success. On error, clears the server's
pool and marks the server Unknown.
Re-raises any exception thrown by fn().
"""
try:
return func(*args, **kwargs)
except NetworkTimeout:
# The socket has been closed. Don't reset the server.
raise
except ConnectionFailure:
self.__reset_server(server.description.address)
raise
示例3: dbUpdate
# 需要导入模块: from pymongo import errors [as 别名]
# 或者: from pymongo.errors import ConnectionFailure [as 别名]
def dbUpdate(self, dbName, collectionName, d, flt, upsert=False):
"""向MongoDB中更新数据,d是具体数据,flt是过滤条件,upsert代表若无是否要插入"""
try:
if self.dbClient:
db = self.dbClient[dbName]
collection = db[collectionName]
collection.replace_one(flt, d, upsert)
else:
self.writeLog(text.DATA_UPDATE_FAILED)
if self.db_has_connected:
self.writeLog(u'重新尝试连接数据库')
self.dbConnect()
except AutoReconnect as ex:
self.writeError(u'数据库连接断开重连:{}'.format(str(ex)))
time.sleep(1)
except ConnectionFailure:
self.dbClient = None
self.writeError(u'数据库连接断开')
if self.db_has_connected:
self.writeLog(u'重新尝试连接数据库')
self.dbConnect()
except Exception as ex:
self.writeError(u'dbUpdate exception:{}'.format(str(ex)))
示例4: search
# 需要导入模块: from pymongo import errors [as 别名]
# 或者: from pymongo.errors import ConnectionFailure [as 别名]
def search(self, uri_query, type_search):
"""
Search endpoints or resources.
:param uri_query: parameters to search
:param type_search: it's equal to ep if the search is for endpoints or res if it is for resources
:return: the string of results or an error code
"""
if (type_search != "ep") and (type_search != "res"):
return defines.Codes.BAD_REQUEST.number
if len(uri_query) <= 0:
uri_query = "ep=*"
query = self.parse_uri_query(uri_query)
query_rdp, query_res = self.split_queries(query)
try:
query = [{"$match": {"$and": [query_rdp, {"$expr": {"$gt": [{"$sum": ["$lt", "$time"]}, int(time())]}}]}},
{"$unwind": "$links"}, {"$match": query_res}]
result = self.collection.aggregate(query)
link = self.serialize_core_link_format(result, type_search)
return link
except ConnectionFailure:
logger.error("Connection to the database cannot be made or is lost.")
return defines.Codes.SERVICE_UNAVAILABLE.number
except OperationFailure as e:
logger.error("Search operation failure with type of search " + type_search + " and uri query " + uri_query + " " +e.message)
return defines.Codes.SERVICE_UNAVAILABLE.number
示例5: update
# 需要导入模块: from pymongo import errors [as 别名]
# 或者: from pymongo.errors import ConnectionFailure [as 别名]
def update(self, resource, uri_query):
"""
Update a registration resource.
:param resource: the resource to update
:param uri_query: the parameters of the registration resource to update
:return: the code of the response
"""
if len(resource) <= 0:
return defines.Codes.BAD_REQUEST.number
data = {}
if len(uri_query) > 0:
data = self.parse_uri_query(uri_query)
res = {'res': resource}
try:
data.update({"time": int(time())})
result = self.collection.update_one(res, {"$set": data})
if not result.matched_count:
return defines.Codes.NOT_FOUND.number
return defines.Codes.CHANGED.number
except ConnectionFailure:
logger.error("Connection to the database cannot be made or is lost.")
return defines.Codes.SERVICE_UNAVAILABLE.number
except OperationFailure:
logger.error("Update operation failure on resource " + resource + " and with uri query " + uri_query)
return defines.Codes.SERVICE_UNAVAILABLE.number
示例6: delete
# 需要导入模块: from pymongo import errors [as 别名]
# 或者: from pymongo.errors import ConnectionFailure [as 别名]
def delete(self, resource):
"""
Delete an endpoint and all its resources
:param resource: the registration resource to delete
:return: the code of the response
"""
res = {'res': resource}
try:
result = self.collection.delete_one(res)
if not result.deleted_count:
return defines.Codes.NOT_FOUND.number
return defines.Codes.DELETED.number
except ConnectionFailure:
logger.error("Connection to the database cannot be made or is lost.")
return defines.Codes.SERVICE_UNAVAILABLE.number
except OperationFailure:
logger.error("Delete operation failure on resource " + resource)
return defines.Codes.SERVICE_UNAVAILABLE.number
示例7: dbConnect
# 需要导入模块: from pymongo import errors [as 别名]
# 或者: from pymongo.errors import ConnectionFailure [as 别名]
def dbConnect(self):
"""连接MongoDB数据库"""
if not self.dbClient:
# 读取MongoDB的设置
host, port = loadMongoSetting()
try:
# 设置MongoDB操作的超时时间为0.5秒
self.dbClient = MongoClient(host, port, serverSelectionTimeoutMS=500)
# 调用server_info查询服务器状态,防止服务器异常并未连接成功
self.dbClient.server_info()
self.writeLog(u'MongoDB连接成功')
except ConnectionFailure:
self.writeLog(u'MongoDB连接失败')
#----------------------------------------------------------------------
示例8: _executeAdminCommand
# 需要导入模块: from pymongo import errors [as 别名]
# 或者: from pymongo.errors import ConnectionFailure [as 别名]
def _executeAdminCommand(self, cluster_object: V1MongoClusterConfiguration, mongo_command: str, *args, **kwargs
) -> Optional[Dict[str, any]]:
"""
Executes the given mongo command on the MongoDB cluster.
Retries a few times in case we receive a handshake failure.
:param name: The name of the cluster.
:param namespace: The namespace of the cluster.
:param mongo_command: The command to be executed in mongo.
:return: The response from MongoDB. See files in `tests/fixtures/mongo_responses` for examples.
:raise ValueError: If the result could not be parsed.
:raise TimeoutError: If we could not connect after retrying.
"""
for _ in range(self.MONGO_COMMAND_RETRIES):
try:
name = cluster_object.metadata.name
if name not in self._connected_replica_sets:
self._connected_replica_sets[name] = self._createMongoClientForReplicaSet(cluster_object)
return self._connected_replica_sets[name].admin.command(mongo_command, *args, **kwargs)
except ConnectionFailure as err:
logging.error("Exception while trying to connect to Mongo: %s", str(err))
logging.info("Command timed out, waiting %s seconds before trying again (attempt %s/%s)",
self.MONGO_COMMAND_WAIT, _, self.MONGO_COMMAND_RETRIES)
sleep(self.MONGO_COMMAND_WAIT)
raise TimeoutError("Could not execute command after {} retries!".format(self.MONGO_COMMAND_RETRIES))
示例9: dbConnect
# 需要导入模块: from pymongo import errors [as 别名]
# 或者: from pymongo.errors import ConnectionFailure [as 别名]
def dbConnect(self):
"""连接MongoDB数据库"""
if not self.dbClient:
# 读取MongoDB的设置
host, port, logging = loadMongoSetting()
try:
# 设置MongoDB操作的超时时间为0.5秒
self.dbClient = MongoClient(host, port, connectTimeoutMS=500)
# 调用server_info查询服务器状态,防止服务器异常并未连接成功
self.dbClient.server_info()
self.writeLog(u'MongoDB连接成功')
# 如果启动日志记录,则注册日志事件监听函数
if logging:
self.eventEngine.register(EVENT_LOG, self.dbLogging)
except ConnectionFailure:
self.writeLog(u'MongoDB连接失败')
#----------------------------------------------------------------------
示例10: connect
# 需要导入模块: from pymongo import errors [as 别名]
# 或者: from pymongo.errors import ConnectionFailure [as 别名]
def connect(self):
"""Connects to Mongo database, loads options and set connectors.
@raise CuckooReportError: if unable to connect.
"""
host = self.options.get("host", "127.0.0.1")
port = self.options.get("port", 27017)
db = self.options.get("db", "cuckoo")
try:
self.conn = MongoClient(host, port)
self.db = self.conn[db]
self.fs = GridFS(self.db)
except TypeError:
raise CuckooReportError("Mongo connection port must be integer")
except ConnectionFailure:
raise CuckooReportError("Cannot connect to MongoDB")
示例11: _get_socket
# 需要导入模块: from pymongo import errors [as 别名]
# 或者: from pymongo.errors import ConnectionFailure [as 别名]
def _get_socket(self, selector):
server = self._get_topology().select_server(selector)
try:
with server.get_socket(self.__all_credentials) as sock_info:
yield sock_info
except NetworkTimeout:
# The socket has been closed. Don't reset the server.
# Server Discovery And Monitoring Spec: "When an application
# operation fails because of any network error besides a socket
# timeout...."
raise
except NotMasterError:
# "When the client sees a "not master" error it MUST replace the
# server's description with type Unknown. It MUST request an
# immediate check of the server."
self._reset_server_and_request_check(server.description.address)
raise
except ConnectionFailure:
# "Client MUST replace the server's description with type Unknown
# ... MUST NOT request an immediate check of the server."
self.__reset_server(server.description.address)
raise
示例12: exists
# 需要导入模块: from pymongo import errors [as 别名]
# 或者: from pymongo.errors import ConnectionFailure [as 别名]
def exists(self, workflow_id):
""" Checks whether a document with the specified workflow id already exists.
Args:
workflow_id (str): The workflow id that should be checked.
Raises:
DataStoreNotConnected: If the data store is not connected to the server.
Returns:
bool: ``True`` if a document with the specified workflow id exists.
"""
try:
db = self._client[self.database]
col = db[WORKFLOW_DATA_COLLECTION_NAME]
return col.find_one({"_id": ObjectId(workflow_id)}) is not None
except ConnectionFailure:
raise DataStoreNotConnected()
示例13: add
# 需要导入模块: from pymongo import errors [as 别名]
# 或者: from pymongo.errors import ConnectionFailure [as 别名]
def add(self, payload=None):
""" Adds a new document to the data store and returns its id.
Args:
payload (dict): Dictionary of initial data that should be stored
in the new document in the meta section.
Raises:
DataStoreNotConnected: If the data store is not connected to the server.
Returns:
str: The id of the newly created document.
"""
try:
db = self._client[self.database]
col = db[WORKFLOW_DATA_COLLECTION_NAME]
return str(col.insert_one({
DataStoreDocumentSection.Meta:
payload if isinstance(payload, dict) else {},
DataStoreDocumentSection.Data: {}
}).inserted_id)
except ConnectionFailure:
raise DataStoreNotConnected()
示例14: remove
# 需要导入模块: from pymongo import errors [as 别名]
# 或者: from pymongo.errors import ConnectionFailure [as 别名]
def remove(self, workflow_id):
""" Removes a document specified by its id from the data store.
All associated GridFs documents are deleted as well.
Args:
workflow_id (str): The id of the document that represents a workflow run.
Raises:
DataStoreNotConnected: If the data store is not connected to the server.
"""
try:
db = self._client[self.database]
fs = GridFSProxy(GridFS(db.unproxied_object))
for grid_doc in fs.find({"workflow_id": workflow_id},
no_cursor_timeout=True):
fs.delete(grid_doc._id)
col = db[WORKFLOW_DATA_COLLECTION_NAME]
return col.delete_one({"_id": ObjectId(workflow_id)})
except ConnectionFailure:
raise DataStoreNotConnected()
示例15: __init__
# 需要导入模块: from pymongo import errors [as 别名]
# 或者: from pymongo.errors import ConnectionFailure [as 别名]
def __init__(self, ip="127.0.0.1", port=27017, dbname="pastepwn", collectionname="pastes"):
super().__init__()
self.logger = logging.getLogger(__name__)
self.logger.debug("Initializing MongoDB - {0}:{1}".format(ip, port))
self.db = pymongo.MongoClient(ip, port, serverSelectionTimeoutMS=5000)
try:
self.db.admin.command("ismaster")
except ConnectionFailure as e:
self.logger.error(e)
raise e
self.logger.debug("Connected to database!")
self.db = self.db[dbname]
self.collection = self.db[collectionname]
self.collection.create_index([('key', pymongo.ASCENDING)], unique=True)