本文整理匯總了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]
示例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()
示例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()
示例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())
示例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()
示例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()
示例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'])
示例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
示例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
示例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
示例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
示例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)
示例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)])
示例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)
示例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()