我们从Python开源项目中,提取了以下31个代码示例,用于说明如何使用pymongo.errors.InvalidName()。
def get_conn(): """ Get a database connection Ensures that only one global database connection exists per thread. If the connection does not exist a new one is created and returned. """ if external_client is not None: return external_client global __client, __connection if not __connection: try: __client = MongoClient(mongo_addr, mongo_port) __connection = __client[mongo_db_name] except ConnectionFailure: raise SevereInternalException("Could not connect to mongo database {} at {}:{}".format(mongo_db_name, mongo_addr, mongo_port)) except InvalidName as error: raise SevereInternalException("Database {} is invalid! - {}".format(mongo_db_name, error)) return __connection
def _get_collection(self, collection_name): """ Get PyMongo client pointing to the current DB and the given collection. :return: MongoDB client of the current database and given collection. :raise DataSourceError """ try: return self._database[collection_name] except InvalidName as ex: raise DataSourceError("Cannot access MongoDB collection %s!" % collection_name) from ex except Exception as ex: raise DataSourceError("Unexpected error when accessing MongoDB" "collection %s!" % collection_name) from ex
def get_conn(): """ Get a database connection Ensures that only one global database connection exists per thread. If the connection does not exist a new one is created and returned. """ global __client, __connection if not __connection: try: # Allow more complex mongodb connections conf = api.app.app.config if conf["MONGO_USER"] and conf["MONGO_PW"]: uri = "mongodb://{}:{}@{}:{}/{}?authMechanism=SCRAM-SHA-1".format( conf["MONGO_USER"], conf["MONGO_PW"], conf["MONGO_ADDR"], conf["MONGO_PORT"], conf["MONGO_DB_NAME"]) else: uri = "mongodb://{}:{}/{}".format( conf["MONGO_ADDR"], conf["MONGO_PORT"], conf["MONGO_DB_NAME"]) __client = MongoClient(uri) __connection = __client[conf["MONGO_DB_NAME"]] except ConnectionFailure: raise SevereInternalException("Could not connect to mongo database {} at {}:{}".format(mongo_db_name, mongo_addr, mongo_port)) except InvalidName as error: raise SevereInternalException("Database {} is invalid! - {}".format(mongo_db_name, error)) return __connection
def __getattr__(self, name): """Get a sub-collection of this collection by name. Raises InvalidName if an invalid collection name is used. :Parameters: - `name`: the name of the collection to get """ if name.startswith('_'): full_name = _UJOIN % (self.__name, name) raise AttributeError( "Collection has no attribute %r. To access the %s" " collection, use database['%s']." % ( name, full_name, full_name)) return self.__getitem__(name)
def rename(self, new_name, **kwargs): """Rename this collection. If operating in auth mode, client must be authorized as an admin to perform this operation. Raises :class:`TypeError` if `new_name` is not an instance of :class:`basestring` (:class:`str` in python 3). Raises :class:`~pymongo.errors.InvalidName` if `new_name` is not a valid collection name. :Parameters: - `new_name`: new name for this collection - `**kwargs` (optional): additional arguments to the rename command may be passed as keyword arguments to this helper method (i.e. ``dropTarget=True``) """ if not isinstance(new_name, string_type): raise TypeError("new_name must be an " "instance of %s" % (string_type.__name__,)) if not new_name or ".." in new_name: raise InvalidName("collection names cannot be empty") if new_name[0] == "." or new_name[-1] == ".": raise InvalidName("collecion names must not start or end with '.'") if "$" in new_name and not new_name.startswith("oplog.$main"): raise InvalidName("collection names must not contain '$'") new_name = "%s.%s" % (self.__database.name, new_name) cmd = SON([("renameCollection", self.__full_name), ("to", new_name)]) cmd.update(kwargs) with self._socket_for_writes() as sock_info: sock_info.command('admin', cmd)
def __getattr__(self, name): """Get a sub-collection of this collection by name. Raises InvalidName if an invalid collection name is used. :Parameters: - `name`: the name of the collection to get """ return Collection(self.__database, u"%s.%s" % (self.__name, name))
def rename(self, new_name, **kwargs): """Rename this collection. If operating in auth mode, client must be authorized as an admin to perform this operation. Raises :class:`TypeError` if `new_name` is not an instance of :class:`basestring` (:class:`str` in python 3). Raises :class:`~pymongo.errors.InvalidName` if `new_name` is not a valid collection name. :Parameters: - `new_name`: new name for this collection - `**kwargs` (optional): any additional rename options should be passed as keyword arguments (i.e. ``dropTarget=True``) .. versionadded:: 1.7 support for accepting keyword arguments for rename options """ if not isinstance(new_name, basestring): raise TypeError("new_name must be an instance " "of %s" % (basestring.__name__,)) if not new_name or ".." in new_name: raise InvalidName("collection names cannot be empty") if new_name[0] == "." or new_name[-1] == ".": raise InvalidName("collecion names must not start or end with '.'") if "$" in new_name and not new_name.startswith("oplog.$main"): raise InvalidName("collection names must not contain '$'") new_name = "%s.%s" % (self.__database.name, new_name) self.__database.connection.admin.command("renameCollection", self.__full_name, to=new_name, **kwargs)
def rename(self, new_name, **kwargs): """Rename this collection. If operating in auth mode, client must be authorized as an admin to perform this operation. Raises :class:`TypeError` if `new_name` is not an instance of :class:`basestring` (:class:`str` in python 3). Raises :class:`~pymongo.errors.InvalidName` if `new_name` is not a valid collection name. :Parameters: - `new_name`: new name for this collection - `**kwargs` (optional): any additional rename options should be passed as keyword arguments (i.e. ``dropTarget=True``) .. versionadded:: 1.7 support for accepting keyword arguments for rename options """ if not isinstance(new_name, basestring): raise TypeError("new_name must be an instance " "of %s" % (basestring.__name__,)) if not new_name or ".." in new_name: raise InvalidName("collection names cannot be empty") if new_name[0] == "." or new_name[-1] == ".": raise InvalidName("collecion names must not start or end with '.'") if "$" in new_name and not new_name.startswith("oplog.$main"): raise InvalidName("collection names must not contain '$'") new_name = "%s.%s" % (self.__database.name, new_name) client = self.__database.connection client.admin.command("renameCollection", self.__full_name, read_preference=ReadPreference.PRIMARY, to=new_name, **kwargs)
def __init__(self, database: 'aiomongo.Database', name: str, read_preference: Optional[Union[_ALL_READ_PREFERENCES]] = None, read_concern: Optional[ReadConcern] = None, codec_options: Optional[CodecOptions] = None, write_concern: Optional[WriteConcern] = None): if not name or '..' in name: raise InvalidName('collection names cannot be empty') if '$' in name and not (name.startswith('oplog.$main') or name.startswith('$cmd')): raise InvalidName('collection names must not ' 'contain "$": {}'.format(name)) if name[0] == '.' or name[-1] == '.': raise InvalidName('collection names must not start ' 'or end with ".": {}'.format(name)) if '\x00' in name: raise InvalidName('collection names must not contain the ' 'null character') self.database = database self.read_preference = read_preference or database.read_preference self.read_concern = read_concern or database.read_concern self.write_concern = write_concern or database.write_concern self.codec_options = codec_options or database.codec_options self.name = name self.__write_response_codec_options = self.codec_options._replace( unicode_decode_error_handler='replace', document_class=dict)
def rename(self, new_name: str, **kwargs) -> None: """Rename this collection. If operating in auth mode, client must be authorized as an admin to perform this operation. Raises :class:`TypeError` if `new_name` is not an instance of :class:`basestring` (:class:`str` in python 3). Raises :class:`~pymongo.errors.InvalidName` if `new_name` is not a valid collection name. :Parameters: - `new_name`: new name for this collection - `**kwargs` (optional): additional arguments to the rename command may be passed as keyword arguments to this helper method (i.e. ``dropTarget=True``) """ if not isinstance(new_name, str): raise TypeError('new_name must be an instance of str') if not new_name or '..' in new_name: raise InvalidName('collection names cannot be empty') if new_name[0] == '.' or new_name[-1] == '.': raise InvalidName('collection names must not start or end with \'.\'') if '$' in new_name and not new_name.startswith('oplog.$main'): raise InvalidName('collection names must not contain \'$\'') new_name = '{}.{}'.format(self.database.name, new_name) cmd = SON([('renameCollection', str(self)), ('to', new_name)]) cmd.update(kwargs) connection = await self.database.client.get_connection() await connection.command('admin', cmd, ReadPreference.PRIMARY, self.codec_options)
def __getattr__(self, name: str) -> 'Collection': """Get a sub-collection of this collection by name. Raises InvalidName if an invalid collection name is used. :Parameters: - `name`: the name of the collection to get """ if name.startswith('_'): full_name = '{}.{}'.format(self.name, name) raise AttributeError( 'Collection has no attribute {}. To access the {}' ' collection, use database["{}"].'.format( name, full_name, full_name)) return self.__getitem__(name)
def _get_database(self, database_name): """ Get PyMongo client pointing to the current database. :return: MongoDB client of the current database. :raise DataSourceError """ try: return self._client[database_name] except InvalidName as ex: raise DataSourceError("Cannot connect to database %s!" % self._database) from ex
def rename(self, new_name, **kwargs): """Rename this collection. If operating in auth mode, client must be authorized as an admin to perform this operation. Raises :class:`TypeError` if `new_name` is not an instance of :class:`basestring` (:class:`str` in python 3). Raises :class:`~pymongo.errors.InvalidName` if `new_name` is not a valid collection name. :Parameters: - `new_name`: new name for this collection - `**kwargs` (optional): additional arguments to the rename command may be passed as keyword arguments to this helper method (i.e. ``dropTarget=True``) .. note:: The :attr:`~pymongo.collection.Collection.write_concern` of this collection is automatically applied to this operation when using MongoDB >= 3.4. .. versionchanged:: 3.4 Apply this collection's write concern automatically to this operation when connected to MongoDB >= 3.4. """ if not isinstance(new_name, string_type): raise TypeError("new_name must be an " "instance of %s" % (string_type.__name__,)) if not new_name or ".." in new_name: raise InvalidName("collection names cannot be empty") if new_name[0] == "." or new_name[-1] == ".": raise InvalidName("collecion names must not start or end with '.'") if "$" in new_name and not new_name.startswith("oplog.$main"): raise InvalidName("collection names must not contain '$'") new_name = "%s.%s" % (self.__database.name, new_name) cmd = SON([("renameCollection", self.__full_name), ("to", new_name)]) with self._socket_for_writes() as sock_info: if sock_info.max_wire_version >= 5 and self.write_concern: cmd['writeConcern'] = self.write_concern.document cmd.update(kwargs) sock_info.command('admin', cmd, parse_write_concern_error=True)