当前位置: 首页>>代码示例>>Python>>正文


Python database.Database方法代码示例

本文整理汇总了Python中pymongo.database.Database方法的典型用法代码示例。如果您正苦于以下问题:Python database.Database方法的具体用法?Python database.Database怎么用?Python database.Database使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在pymongo.database的用法示例。


在下文中一共展示了database.Database方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: get_mongodb_connection

# 需要导入模块: from pymongo import database [as 别名]
# 或者: from pymongo.database import Database [as 别名]
def get_mongodb_connection(host: str,
                           port: Union[str, int],
                           user: str,
                           password: str,
                           database: str,
                           auth_database: str)->Database:
    """
    Creates a mongoDB connection to the db to sync from
    Returns: Database instance with established connection

    """
    return pymongo.MongoClient(host=host,
                               port=int(port),
                               username=user,
                               password=password,
                               authSource=auth_database)[database] 
开发者ID:transferwise,项目名称:pipelinewise,代码行数:18,代码来源:db.py

示例2: __init__

# 需要导入模块: from pymongo import database [as 别名]
# 或者: from pymongo.database import Database [as 别名]
def __init__(self, database, collection="fs", _connect=True):
        """Create a new instance of :class:`GridFS`.

        Raises :class:`TypeError` if `database` is not an instance of
        :class:`~pymongo.database.Database`.

        :Parameters:
          - `database`: database to use
          - `collection` (optional): root collection to use

        .. versionadded:: 1.6
           The `collection` parameter.

        .. mongodoc:: gridfs
        """
        if not isinstance(database, Database):
            raise TypeError("database must be an instance of Database")

        self.__database = database
        self.__collection = database[collection]
        self.__files = self.__collection.files
        self.__chunks = self.__collection.chunks
        if _connect:
            self.__ensure_index_files_id() 
开发者ID:Frank-qlu,项目名称:recruit,代码行数:26,代码来源:__init__.py

示例3: test_copy_table_with_collection_found_but_export_failed_expect_exception

# 需要导入模块: from pymongo import database [as 别名]
# 或者: from pymongo.database import Database [as 别名]
def test_copy_table_with_collection_found_but_export_failed_expect_exception(self):
        """
        Test copy_table method with a collection name that's not found in the db, thus raising a TableNotFoundError
        error
        """
        self.mongo.database = Mock(spec_set=Database).return_value
        self.mongo.database.list_collection_names.return_value = ['col1', 'col2', 'col3', 'my_col']

        with patch('pipelinewise.fastsync.commons.tap_mongodb.subprocess.call') as call_mock:
            call_mock.return_value = 1

            with self.assertRaises(ExportError):
                self.mongo.copy_table('my_col', 'file.csv.gzip', 'tmp')

            call_mock.assert_called_once_with([
                'mongodump',
                '--uri', '"mongodb://my_user:secret@foo.com:3306/my_db?authSource=admin"',
                '--forceTableScan',
                '--gzip',
                '-c', 'my_col',
                '-o', 'tmp'
            ])

        self.mongo.database.list_collection_names.assert_called_once() 
开发者ID:transferwise,项目名称:pipelinewise,代码行数:26,代码来源:test_fastsync_tap_mongodb.py

示例4: test_fetch_current_log_pos_return_first_token

# 需要导入模块: from pymongo import database [as 别名]
# 或者: from pymongo.database import Database [as 别名]
def test_fetch_current_log_pos_return_first_token(self):
        """
        Test fetch_current_log_pos should return the the first encountered token
        """
        cursor_mock = Mock(spec_set=DatabaseChangeStream).return_value
        type(cursor_mock).alive = PropertyMock(return_value=True)
        type(cursor_mock).resume_token = PropertyMock(side_effect=['token1', 'token2',
                                                                   'token3', 'token4'])
        cursor_mock.try_next.side_effect = [{}, {}, {}]

        mock_enter = Mock()
        mock_enter.return_value = cursor_mock

        mock_watch = Mock().return_value
        mock_watch.__enter__ = mock_enter
        mock_watch.__exit__ = Mock()

        self.mongo.database = Mock(spec_set=Database).return_value
        self.mongo.database.watch.return_value = mock_watch

        self.assertDictEqual({
            'token': 'token1'
        }, self.mongo.fetch_current_log_pos()) 
开发者ID:transferwise,项目名称:pipelinewise,代码行数:25,代码来源:test_fastsync_tap_mongodb.py

示例5: __init__

# 需要导入模块: from pymongo import database [as 别名]
# 或者: from pymongo.database import Database [as 别名]
def __init__(self,
                 domain,
                 host="mongodb://localhost:27017",
                 db="rasa",
                 username=None,
                 password=None,
                 auth_source="admin",
                 collection="conversations",
                 event_broker=None):
        from pymongo.database import Database
        from pymongo import MongoClient

        self.client = MongoClient(host,
                                  username=username,
                                  password=password,
                                  authSource=auth_source,
                                  # delay connect until process forking is done
                                  connect=False)

        self.db = Database(self.client, db)
        self.collection = collection
        super(MongoTrackerStore, self).__init__(domain, event_broker)

        self._ensure_indices() 
开发者ID:RasaHQ,项目名称:rasa_core,代码行数:26,代码来源:tracker_store.py

示例6: __init__

# 需要导入模块: from pymongo import database [as 别名]
# 或者: from pymongo.database import Database [as 别名]
def __init__(self,
                 client_connection: MongoClient,
                 db_connection: Database,
                 connection_properties: 'base.DjongoClient',
                 sql: str,
                 params: Optional[Sequence]):

        self._params = params
        self.db = db_connection
        self.cli_con = client_connection
        self.connection_properties = connection_properties
        self._params_index_count = -1
        self._sql = re.sub(r'%s', self._param_index, sql)
        self.last_row_id = None
        self._result_generator = None

        self._query = self.parse() 
开发者ID:nesdis,项目名称:djongo,代码行数:19,代码来源:query.py

示例7: get_connection

# 需要导入模块: from pymongo import database [as 别名]
# 或者: from pymongo.database import Database [as 别名]
def get_connection() -> database.Database:
    """在连接池中获得连接"""
    if not has_app_context():
        config = get_config()
        return MongoClient(**config.MONGODB).get_database(config.MONGODB_DB)
    return current_app.mongo.get_database(current_app.config['MONGODB_DB']) 
开发者ID:everyclass,项目名称:everyclass-server,代码行数:8,代码来源:mongodb.py

示例8: test_authenticate

# 需要导入模块: from pymongo import database [as 别名]
# 或者: from pymongo.database import Database [as 别名]
def test_authenticate():
    db = create_autospec(Database)
    db.authenticate.return_value = sentinel.ret
    assert auth.authenticate(db, sentinel.user, sentinel.password) == sentinel.ret 
开发者ID:man-group,项目名称:arctic,代码行数:6,代码来源:test_auth.py

示例9: test_authenticate_fails

# 需要导入模块: from pymongo import database [as 别名]
# 或者: from pymongo.database import Database [as 别名]
def test_authenticate_fails():
    db = create_autospec(Database)
    error = "command SON([('saslStart', 1), ('mechanism', 'SCRAM-SHA-1'), ('payload', Binary('n,,n=foo,r=OTI3MzA3MTEzMTIx', 0)), ('autoAuthorize', 1)]) on namespace admin.$cmd failed: Authentication failed."
    db.authenticate.side_effect = OperationFailure(error)
    assert auth.authenticate(db, sentinel.user, sentinel.password) is False 
开发者ID:man-group,项目名称:arctic,代码行数:7,代码来源:test_auth.py

示例10: test_authenticate_fails_exception

# 需要导入模块: from pymongo import database [as 别名]
# 或者: from pymongo.database import Database [as 别名]
def test_authenticate_fails_exception():
    db = create_autospec(Database)
    db.authenticate.side_effect = PyMongoError("error")
    with pytest.raises(PyMongoError):
        assert auth.authenticate(db, sentinel.user, sentinel.password) is False 
开发者ID:man-group,项目名称:arctic,代码行数:7,代码来源:test_auth.py

示例11: get_retweet_user

# 需要导入模块: from pymongo import database [as 别名]
# 或者: from pymongo.database import Database [as 别名]
def get_retweet_user(inputs):
    """
    This function searches engaged users which re-tweet the original tweet(tweet_id)
    :param inputs: tuple which have tweet_id and rating(True/False)
    :return: tuple(engaged_user_vector: np.array, rating: 1/0)
    """
    chunk, labeled_users, db_config, limit = inputs
    results = []

    client = MongoClient(**{
        'host': db_config['host'],
        'port': db_config['port']
    })
    db: Database = client[db_config['db']]
    tweets_collections: Collection = db[db_config['collection']]

    for tweet_id, user_id, tweet_text, rating, created_at in chunk:
        query = tweets_collections.find({"retweeted_status.id": tweet_id}).sort([("created_at", 1)]).limit(limit)
        engaged_users = []

        for tweet in query:
            engaged_users.append(tweet['user'])

        if len(engaged_users) == 0:
            continue

        if len(engaged_users) < limit:
            engaged_users.extend([random.choice(engaged_users) for i in range(limit - len(engaged_users))])
            engaged_users.sort(key=lambda x: x['created_at'])

        engaged_users_vector = [User(user).vector.tolist() for user in engaged_users]

        if rating:
            rating = 1
        else:
            rating = 0

        if engaged_users_vector:
            results.append((engaged_users_vector, tweet_text, rating, user_id, str(created_at)))

    return results 
开发者ID:yumere,项目名称:early-fakenews-detection,代码行数:43,代码来源:prepare_dataset.py

示例12: __getattr__

# 需要导入模块: from pymongo import database [as 别名]
# 或者: from pymongo.database import Database [as 别名]
def __getattr__(self, name):
        """Get a database by name.

        Raises InvalidName if an invalid database name is used.

        :Parameters:
          - `name`: the name of the database to get
        """
        return Database(self, name) 
开发者ID:Frank-qlu,项目名称:recruit,代码行数:11,代码来源:master_slave_connection.py

示例13: __init__

# 需要导入模块: from pymongo import database [as 别名]
# 或者: from pymongo.database import Database [as 别名]
def __init__(self, client: Database):
        self._client = client
        self._client.projects.create_index([("name", DESCENDING)]) 
开发者ID:psincraian,项目名称:pepy,代码行数:5,代码来源:db_repository.py

示例14: test_open_connections

# 需要导入模块: from pymongo import database [as 别名]
# 或者: from pymongo.database import Database [as 别名]
def test_open_connections(self):
        """
            Test open_connection method
            it should create a Database Mock
        """
        with patch('pipelinewise.fastsync.commons.tap_mongodb.MongoClient') as mongo_client_mock:
            mongo_client_mock.return_value = {
                'my_db': Mock(spec_set=Database)
            }
            self.mongo.open_connection()

        self.assertIsInstance(self.mongo.database, Mock) 
开发者ID:transferwise,项目名称:pipelinewise,代码行数:14,代码来源:test_fastsync_tap_mongodb.py

示例15: test_close_connection

# 需要导入模块: from pymongo import database [as 别名]
# 或者: from pymongo.database import Database [as 别名]
def test_close_connection(self):
        """
        Test close_connection method, It should call the close method on the client
        """
        self.mongo.database = Mock(spec_set=Database)

        client = Mock(spec_set=MongoClient)
        client.return_value.close.side_effect = True

        type(self.mongo.database).client = PropertyMock(return_value=client)

        self.mongo.close_connection()

        client.close.assert_called_once() 
开发者ID:transferwise,项目名称:pipelinewise,代码行数:16,代码来源:test_fastsync_tap_mongodb.py


注:本文中的pymongo.database.Database方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。