本文整理汇总了Python中pymongo.MongoClient方法的典型用法代码示例。如果您正苦于以下问题:Python pymongo.MongoClient方法的具体用法?Python pymongo.MongoClient怎么用?Python pymongo.MongoClient使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类pymongo
的用法示例。
在下文中一共展示了pymongo.MongoClient方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: get_mongodb_connection
# 需要导入模块: import pymongo [as 别名]
# 或者: from pymongo import MongoClient [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: get_db
# 需要导入模块: import pymongo [as 别名]
# 或者: from pymongo import MongoClient [as 别名]
def get_db():
"""Retrieve a MongoDB client using the settings in db_conf."""
global db
if not db:
if db_conf["MONGO_USER"] or db_conf["MONGO_PASS"]:
mongo_client = MongoClient(
"mongodb://{}:{}@{}:{}/{}?authMechanism=SCRAM-SHA-1".format(
db_conf["MONGO_USER"],
db_conf["MONGO_PASS"],
db_conf["MONGO_HOST"],
db_conf["MONGO_PORT"],
db_conf["MONGO_DB_NAME"],
)
)
else:
mongo_client = MongoClient(
"mongodb://{}:{}/{}".format(
db_conf["MONGO_HOST"],
db_conf["MONGO_PORT"],
db_conf["MONGO_DB_NAME"],
)
)
db = mongo_client[db_conf["MONGO_DB_NAME"]]
return db
示例3: __init__
# 需要导入模块: import pymongo [as 别名]
# 或者: from pymongo import MongoClient [as 别名]
def __init__(self, name=None, host='127.0.0.1', port=27017, clients=None):
'''
args:
Clients : dict filled with name of client and MongoClient
dict(name = client)
'''
self.clients = dict()
# Init default values
self.last_client = None
self.last_db = None
self.last_collection = None
self.runner = []
if clients:
for name, client in clients.items():
self.addClient(client, name)
elif name:
self.addClient(MongoClient(host, port), name)
示例4: addClient
# 需要导入模块: import pymongo [as 别名]
# 或者: from pymongo import MongoClient [as 别名]
def addClient(self, client, name):
'''
Add a new client
args:
client : MongoClient object
name : Name of client as str
'''
dbmErrorHandler.ClientNameError(name)
dbmErrorHandler.ClientError(client)
self.last_client = name
new_client = dict(
client = client,
databases = dict()
)
self.clients[name] = new_client
示例5: __init__
# 需要导入模块: import pymongo [as 别名]
# 或者: from pymongo import MongoClient [as 别名]
def __init__(self, config=None):
self.client = MongoClient()
ratesx_db = self.client.ratesx
self.coins = ratesx_db.coins
self.marketcap = ratesx_db.marketcap
self.currencies = ratesx_db.currencies
if config is None:
config = {}
self.number_of_coins = config.get('number_of_coins', 30)
self.number_of_ticks = config.get('number_of_ticks', 12)
self.currency = config.get('currency', 'USD')
if self.currency in currencies_names.SUPPORTED_CURRENCIES:
self.is_currency_coin = False
else:
self.is_currency_coin = True
self._currency_factor_cache = {}
self._spark_price_currency_ticks = []
示例6: getMongoConnection
# 需要导入模块: import pymongo [as 别名]
# 或者: from pymongo import MongoClient [as 别名]
def getMongoConnection(cls):
mongoHost = cls.readSetting("Mongo", "Host", cls.default['mongoHost'])
mongoPort = cls.readSetting("Mongo", "Port", cls.default['mongoPort'])
mongoDB = cls.getMongoDB()
mongoUsername = cls.readSetting("Mongo", "Username", cls.default['mongoUsername'])
mongoPassword = cls.readSetting("Mongo", "Password", cls.default['mongoPassword'])
mongoUsername = urllib.parse.quote( mongoUsername )
mongoPassword = urllib.parse.quote( mongoPassword )
try:
if mongoUsername and mongoPassword:
mongoURI = "mongodb://{username}:{password}@{host}:{port}/{db}".format(
username = mongoUsername, password = mongoPassword,
host = mongoHost, port = mongoPort,
db = mongoDB
)
connect = pymongo.MongoClient(mongoURI, connect=False)
else:
connect = pymongo.MongoClient(mongoHost, mongoPort, connect=False)
except:
sys.exit("Unable to connect to Mongo. Is it running on %s:%s?"%(mongoHost,mongoPort))
return connect[mongoDB]
示例7: main
# 需要导入模块: import pymongo [as 别名]
# 或者: from pymongo import MongoClient [as 别名]
def main():
usage = """usage: %prog [options] arg1=value, arg2=value
Enables sharding on the specified arctic library.
"""
setup_logging()
parser = optparse.OptionParser(usage=usage)
parser.add_option("--host", default='localhost', help="Hostname, or clustername. Default: localhost")
parser.add_option("--library", help="The name of the library. e.g. 'arctic_jblackburn.lib'")
(opts, _) = parser.parse_args()
if not opts.library or '.' not in opts.library:
parser.error('must specify the full path of the library e.g. arctic_jblackburn.lib!')
print("Enabling-sharding: %s on mongo %s" % (opts.library, opts.host))
c = pymongo.MongoClient(get_mongodb_uri(opts.host))
credentials = get_auth(opts.host, 'admin', 'admin')
if credentials:
authenticate(c.admin, credentials.user, credentials.password)
store = Arctic(c)
enable_sharding(store, opts.library)
示例8: refresh_data
# 需要导入模块: import pymongo [as 别名]
# 或者: from pymongo import MongoClient [as 别名]
def refresh_data(data, collection_name, refresh_period, host, port):
client = MongoClient(host, port)
db = client['deep-architect']
collection = db[collection_name]
while collection.find_one_and_update(
{
'$and': [{
'_id': data['_id']
}, {
STARTTIME_KEY: {
'$ne': None
}
}, {
ENDTIME_KEY: {
'$eq': None
}
}]
}, {'$currentDate': {
REFRESH_KEY: True
}},
return_document=ReturnDocument.AFTER):
logger.debug('Refreshed data for id %s', str(data['_id']))
time.sleep(refresh_period)
示例9: connect
# 需要导入模块: import pymongo [as 别名]
# 或者: from pymongo import MongoClient [as 别名]
def connect(self):
"""Connect to MongoDB"""
if self.__conn is None:
if self.mongo_user is None:
try:
self.__conn = MongoClient('mongodb://%s:%s' %
(self.mongo_host,
self.mongo_port))
except errors.PyMongoError as py_mongo_error:
print('Error in MongoDB connection: %s' %
str(py_mongo_error))
else:
try:
self.__conn = MongoClient('mongodb://%s:%s@%s:%s' %
(self.mongo_user,
self.mongo_password,
self.mongo_host,
self.mongo_port))
except errors.PyMongoError as py_mongo_error:
print('Error in MongoDB connection: %s' %
str(py_mongo_error))
示例10: update_status
# 需要导入模块: import pymongo [as 别名]
# 或者: from pymongo import MongoClient [as 别名]
def update_status(crits_id, status):
assert isinstance(crits_id, str)
assert status in [ 'Informational', 'Analyzed' ]
# API support for changing the status message was not implemented at the time I wrote this
# download the crits indicator JSON directly from the crits mongo database
client = MongoClient(saq.CONFIG['crits']['mongodb_uri'])
db = client['crits']
collection = db['indicators']
logging.debug("updating status of {} to {}".format(crits_id, status))
result = collection.update({'_id': ObjectId(crits_id)}, {'$set': {'status': status}})
# this actually isn't an error, it does not update if the value is the same as previous
#if result['nModified'] != 1:
#logging.error("unable to update crits indicator {}: update count = {}".format(crits_id, reuslt['nModified']))
return result['nModified']
示例11: test_retrieve_project
# 需要导入模块: import pymongo [as 别名]
# 或者: from pymongo import MongoClient [as 别名]
def test_retrieve_project(mongo_client: MongoClient, repository: ProjectRepository):
data = {
"name": "climoji",
"total_downloads": 1100,
"downloads": {
"2020-04-01": [["2.0", 30]],
"2020-04-02": [["2.0", 10]],
"2020-03-31": [["2.0", 40]],
"2020-04-03": [["2.0", 30]],
},
}
query = {"name": "climoji"}
mongo_client.pepy_test.projects.replace_one(query, data, upsert=True)
result = repository.get("climoji")
assert ProjectName("climoji") == result.name
assert datetime.date(2020, 3, 31) == result.min_date
assert Downloads(1100) == result.total_downloads
expected_last_downloads = [
ProjectVersionDownloads(datetime.date(2020, 3, 31), "2.0", Downloads(40)),
ProjectVersionDownloads(datetime.date(2020, 4, 1), "2.0", Downloads(30)),
ProjectVersionDownloads(datetime.date(2020, 4, 2), "2.0", Downloads(10)),
ProjectVersionDownloads(datetime.date(2020, 4, 3), "2.0", Downloads(30)),
]
assert expected_last_downloads == result.last_downloads()
示例12: open_connection
# 需要导入模块: import pymongo [as 别名]
# 或者: from pymongo import MongoClient [as 别名]
def open_connection(self):
"""
Open connection
"""
# Default SSL verify mode to true, give option to disable
verify_mode = self.connection_config.get('verify_mode', 'true') == 'true'
use_ssl = self.connection_config.get('ssl') == 'true'
connection_params = dict(host=self.connection_config['host'], port=int(self.connection_config['port']),
username=self.connection_config['user'], password=self.connection_config['password'],
authSource=self.connection_config['auth_database'], ssl=use_ssl,
replicaSet=self.connection_config.get('replica_set', None),
readPreference='secondaryPreferred')
# NB: "ssl_cert_reqs" must ONLY be supplied if `SSL` is true.
if not verify_mode and use_ssl:
connection_params['ssl_cert_reqs'] = ssl.CERT_NONE
self.database = MongoClient(**connection_params)[self.connection_config['database']]
示例13: mongo_server
# 需要导入模块: import pymongo [as 别名]
# 或者: from pymongo import MongoClient [as 别名]
def mongo_server(unused_port, container_starter):
tag = '3.3'
image = 'mongo:{}'.format(tag)
internal_port = 27017
host_port = unused_port()
volume = str(TEMP_FOLDER / 'docker' / 'mongo'), '/data/db'
command = '--smallfiles'
container = container_starter(image, internal_port, host_port,
volume=volume, command=command)
params = dict(host='127.0.0.1', port=host_port)
def connect():
client = pymongo.MongoClient(**params)
test_coll = client.test.test
test_coll.find_one()
client.close()
wait_for_container(connect, image, pymongo.errors.PyMongoError)
container['params'] = params
return container
示例14: get_conn
# 需要导入模块: import pymongo [as 别名]
# 或者: from pymongo import MongoClient [as 别名]
def get_conn(self):
"""
Fetches PyMongo Client
"""
conn = self.connection
uri = 'mongodb://{creds}{host}{port}/{database}'.format(
creds='{}:{}@'.format(
conn.login, conn.password
) if conn.login is not None else '',
host=conn.host,
port='' if conn.port is None else ':{}'.format(conn.port),
database='' if conn.schema is None else conn.schema
)
# Mongo Connection Options dict that is unpacked when passed to MongoClient
options = self.extras
# If we are using SSL disable requiring certs from specific hostname
if options.get('ssl', False):
options.update({'ssl_cert_reqs': CERT_NONE})
return MongoClient(uri, **options)
示例15: init_pool
# 需要导入模块: import pymongo [as 别名]
# 或者: from pymongo import MongoClient [as 别名]
def init_pool(current_application) -> None:
"""创建连接池,保存在 app 的 mongo 属性中"""
current_application.mongo = MongoClient(**current_application.config['MONGODB'])