本文整理汇总了Python中motor.motor_asyncio.AsyncIOMotorClient方法的典型用法代码示例。如果您正苦于以下问题:Python motor_asyncio.AsyncIOMotorClient方法的具体用法?Python motor_asyncio.AsyncIOMotorClient怎么用?Python motor_asyncio.AsyncIOMotorClient使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类motor.motor_asyncio
的用法示例。
在下文中一共展示了motor_asyncio.AsyncIOMotorClient方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: __init__
# 需要导入模块: from motor import motor_asyncio [as 别名]
# 或者: from motor.motor_asyncio import AsyncIOMotorClient [as 别名]
def __init__(self, config, plugin_manager, loop):
"""Init method for StorageControl class.
Args:
config -- sarlacc config object
plugin_manager -- sarlacc plugin_manager object
loop -- asyncio loop
"""
self.config = config
self.plugin_manager = plugin_manager
self.loop = loop
self.mongo = AsyncIOMotorClient("mongodb://{}:{}".format(
config['mongodb']['host'],
config['mongodb']['port']))
示例2: mongo
# 需要导入模块: from motor import motor_asyncio [as 别名]
# 或者: from motor.motor_asyncio import AsyncIOMotorClient [as 别名]
def mongo(request, loop, mongo_params):
conf = mongo_params.copy()
conf["database"] = "aiohttp_admin_db"
conf["max_pool_size"] = 2
async def init_mogo(conf, loop):
url = "mongodb://{}:{}".format(conf['host'], conf['port'])
conn = aiomotor.AsyncIOMotorClient(
url, maxPoolSize=conf['max_pool_size'], io_loop=loop)
return conn
conn = loop.run_until_complete(init_mogo(conf, loop))
def fin():
conn.close()
request.addfinalizer(fin)
db = conf['database']
return conn[db]
示例3: init_mongo
# 需要导入模块: from motor import motor_asyncio [as 别名]
# 或者: from motor.motor_asyncio import AsyncIOMotorClient [as 别名]
def init_mongo(conf, loop):
mongo_uri = "mongodb://{}:{}".format(conf['host'], conf['port'])
conn = aiomotor.AsyncIOMotorClient(
mongo_uri,
maxPoolSize=conf['max_pool_size'],
io_loop=loop)
db_name = conf['database']
return conn[db_name]
示例4: client
# 需要导入模块: from motor import motor_asyncio [as 别名]
# 或者: from motor.motor_asyncio import AsyncIOMotorClient [as 别名]
def client(self, db):
# motor
self.motor_uri = f"mongodb://localhost:27017/{db}"
return AsyncIOMotorClient(self.motor_uri, io_loop=self.loop)
示例5: __init__
# 需要导入模块: from motor import motor_asyncio [as 别名]
# 或者: from motor.motor_asyncio import AsyncIOMotorClient [as 别名]
def __init__(self, *args, **kwargs):
super().__init__(
command_prefix=self._prefix_callable,
shard_count=self.config.shard_count,
fetch_offline_members=False,
guild_subscriptions=False,
shard_ids=[],
owner_id=self.config.owner_id,
max_messages=10**4,
disabled_events=[
"VOICE_STATE_UPDATE",
"PRESENCE_UPDATE",
"TYPING_START",
"GUILD_EMOJIS_UPDATE"
],
*args, **kwargs
)
self.session = ClientSession(loop=self.loop)
db_connection = AsyncIOMotorClient(
host=self.config.db_host,
username=self.config.db_user,
password=self.config.db_password
)
self.db = getattr(db_connection, self.config.identifier)
for ext in self.config.extensions:
self.load_extension("cogs." + ext)
log.info(f"Loaded {len(self.cogs)} cogs")
示例6: QA_util_sql_async_mongo_setting
# 需要导入模块: from motor import motor_asyncio [as 别名]
# 或者: from motor.motor_asyncio import AsyncIOMotorClient [as 别名]
def QA_util_sql_async_mongo_setting(uri='mongodb://localhost:27017/quantaxis'):
"""
explanation:
根据给定的uri返回一个异步AsyncIOMotorClient实例
params:
* uri ->:
meaning: mongodb连接uri
type: str
optional: [null]
return:
AsyncIOMotorClient
demonstrate:
Not described
output:
Not described
"""
# loop = asyncio.new_event_loop()
# asyncio.set_event_loop(loop)
try:
loop = asyncio.get_event_loop()
except RuntimeError:
loop = asyncio.new_event_loop()
asyncio.set_event_loop(loop)
# async def client():
return AsyncIOMotorClient(uri, io_loop=loop)
# yield client()
示例7: get_db
# 需要导入模块: from motor import motor_asyncio [as 别名]
# 或者: from motor.motor_asyncio import AsyncIOMotorClient [as 别名]
def get_db(uri):
db_name = uri.split('/')[-1]
client = motor_asyncio.AsyncIOMotorClient(uri)
db = client[db_name]
return db
示例8: __init__
# 需要导入模块: from motor import motor_asyncio [as 别名]
# 或者: from motor.motor_asyncio import AsyncIOMotorClient [as 别名]
def __init__(self):
super().__init__(command_prefix=None) # implemented in `get_prefix`
self._session = None
self._api = None
self.metadata_loop = None
self.formatter = SafeFormatter()
self.loaded_cogs = ["cogs.modmail", "cogs.plugins", "cogs.utility"]
self._connected = asyncio.Event()
self.start_time = datetime.utcnow()
self.config = ConfigManager(self)
self.config.populate_cache()
self.threads = ThreadManager(self)
self.log_file_name = os.path.join(temp_dir, f"{self.token.split('.')[0]}.log")
self._configure_logging()
mongo_uri = self.config["mongo_uri"]
if mongo_uri is None:
logger.critical("A Mongo URI is necessary for the bot to function.")
raise RuntimeError
try:
self.db = AsyncIOMotorClient(mongo_uri).modmail_bot
except ConfigurationError as e:
logger.critical(
"Your MONGO_URI might be copied wrong, try re-copying from the source again. "
"Otherwise noted in the following message:"
)
logger.critical(e)
sys.exit(0)
self.plugin_db = PluginDatabaseClient(self)
self.startup()
示例9: init
# 需要导入模块: from motor import motor_asyncio [as 别名]
# 或者: from motor.motor_asyncio import AsyncIOMotorClient [as 别名]
def init(app, loop):
app.db = AsyncIOMotorClient(os.getenv("MONGO_URI")).modmail_bot
app.session = aiohttp.ClientSession(loop=loop)
示例10: on_ready
# 需要导入模块: from motor import motor_asyncio [as 别名]
# 或者: from motor.motor_asyncio import AsyncIOMotorClient [as 别名]
def on_ready():
await bot.change_presence(activity=discord.Game(f"with {len(bot.guilds)} servers | -help | {version}"), afk=True)
url = f"https://discordbots.org/api/bots/{bot.user.id}/stats"
headers = {
'Authorization': dbltoken,
'content-type': 'application/json'
}
payload = {
'server_count': len(bot.guilds)
}
async with aiohttp.ClientSession() as session:
async with session.post(url, data=json.dumps(payload), headers=headers) as dblpost:
print(dblpost.status)
bot._last_result = None
bot.session = aiohttp.ClientSession()
# mongo = AsyncIOMotorClient(bot.auth.get('MONGODB'))
mongo = AsyncIOMotorClient(os.environ.get('mongodb'))
bot.db = mongo.RemixBot
bot.session = aiohttp.ClientSession()
print('Bot is Online.')
# @bot.event
# async def on_message(message):
# channel = message.channel
# if message.author.bot:
# return
# if message.content.lower() in ('whatistheprefix', 'what is the prefix'):
# result = await bot.db.config.find_one({'_id': str(message.guild.id)})
# if not result or not result.get('prefix'):
# prefix = '-'
# else:
# prefix = result.get('prefix')
# await channel.send(f'The guild prefix is `{prefix}`')
# await bot.process_commands(message)
示例11: make_db
# 需要导入模块: from motor import motor_asyncio [as 别名]
# 或者: from motor.motor_asyncio import AsyncIOMotorClient [as 别名]
def make_db():
return AsyncIOMotorClient()[TEST_DB]
示例12: app
# 需要导入模块: from motor import motor_asyncio [as 别名]
# 或者: from motor.motor_asyncio import AsyncIOMotorClient [as 别名]
def app():
app = create_app('config/test.cfg')
# app.client_session = app_session
yield app
client = AsyncIOMotorClient(app.config.MOTOR_URI)
db = client.get_database()
client.drop_database(db)
示例13: __init__
# 需要导入模块: from motor import motor_asyncio [as 别名]
# 或者: from motor.motor_asyncio import AsyncIOMotorClient [as 别名]
def __init__(self, conn_uri=None, db='douyin'):
"""
init save folder
:param folder:
"""
super().__init__()
if not conn_uri:
conn_uri = 'localhost'
self.client = AsyncIOMotorClient(conn_uri)
self.db = self.client[db]
示例14: create_app
# 需要导入模块: from motor import motor_asyncio [as 别名]
# 或者: from motor.motor_asyncio import AsyncIOMotorClient [as 别名]
def create_app(loop, db):
app = web.Application(loop=loop, middlewares=[
session_middleware(SimpleCookieStorage()),
])
app.middlewares.append(aiohttp_login.flash.middleware)
aiohttp_jinja2.setup(
app,
loader=jinja_app_loader.Loader(),
context_processors=[aiohttp_login.flash.context_processor],
)
if db == 'asyncpg':
pool = await asyncpg.create_pool(
dsn='postgres:///' + DATABASE, loop=loop)
storage = AsyncpgStorage(pool)
elif db == 'motor':
app['db'] = AsyncIOMotorClient(io_loop=loop)[DATABASE]
storage = MotorStorage(app['db'])
else:
assert 0, 'unknown storage'
aiohttp_login.setup(app, storage, {
'CSRF_SECRET': 'secret',
'LOGIN_REDIRECT': 'auth_change_email',
'SMTP_SENDER': 'Your Name <your@gmail.com>',
'SMTP_HOST': 'smtp.gmail.com',
'SMTP_PORT': 465,
'SMTP_USERNAME': 'your@gmail.com',
'SMTP_PASSWORD': 'password'
})
@restricted_api
async def api_hello_handler(request):
return {'hello': 'world'}
app.router.add_get('/api/hello', api_hello_handler, name='api_hello')
return app
示例15: on_ready
# 需要导入模块: from motor import motor_asyncio [as 别名]
# 或者: from motor.motor_asyncio import AsyncIOMotorClient [as 别名]
def on_ready():
bot.owner = await bot.fetch_user(SETTINGS.owner_id)
mongo = AsyncIOMotorClient(SETTINGS.mongo_db)
bot.db = mongo.pollmaster
bot.session = aiohttp.ClientSession()
print(bot.db)
# load emoji list
with open('utils/emoji-compact.json', encoding='utf-8') as emojson:
bot.emoji_dict = json.load(emojson)
# # check discord server configs
# try:
# db_server_ids = [entry['_id'] async for entry in bot.db.config.find({}, {})]
# for server in bot.guilds:
# if str(server.id) not in db_server_ids:
# # create new config entry
# await bot.db.config.update_one(
# {'_id': str(server.id)},
# {'$set': {'prefix': 'pm!', 'admin_role': 'polladmin', 'user_role': 'polluser'}},
# upsert=True
# )
# except:
# print("Problem verifying servers.")
# cache prefixes
bot.pre = {entry['_id']: entry.get('prefix', 'pm!') async for entry in bot.db.config.find({}, {'_id', 'prefix'})}
await bot.change_presence(activity=discord.Activity(type=discord.ActivityType.listening, name="pm!help"))
print("Bot running.")