當前位置: 首頁>>代碼示例>>Python>>正文


Python motor_asyncio.AsyncIOMotorClient方法代碼示例

本文整理匯總了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'])) 
開發者ID:scrapbird,項目名稱:sarlacc,代碼行數:18,代碼來源:storage.py

示例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] 
開發者ID:aio-libs,項目名稱:aiohttp_admin,代碼行數:22,代碼來源:db_fixtures.py

示例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] 
開發者ID:aio-libs,項目名稱:aiohttp_admin,代碼行數:10,代碼來源:utils.py

示例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) 
開發者ID:howie6879,項目名稱:ruia,代碼行數:6,代碼來源:db.py

示例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") 
開發者ID:Xenon-Bot,項目名稱:xenon,代碼行數:31,代碼來源:bot.py

示例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() 
開發者ID:QUANTAXIS,項目名稱:QUANTAXIS,代碼行數:33,代碼來源:QASql.py

示例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 
開發者ID:theSage21,項目名稱:openJudge,代碼行數:7,代碼來源:cli.py

示例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() 
開發者ID:kyb3r,項目名稱:modmail,代碼行數:37,代碼來源:bot.py

示例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) 
開發者ID:kyb3r,項目名稱:logviewer,代碼行數:5,代碼來源:app.py

示例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) 
開發者ID:cree-py,項目名稱:RemixBot,代碼行數:43,代碼來源:bot.py

示例11: make_db

# 需要導入模塊: from motor import motor_asyncio [as 別名]
# 或者: from motor.motor_asyncio import AsyncIOMotorClient [as 別名]
def make_db():
    return AsyncIOMotorClient()[TEST_DB] 
開發者ID:Scille,項目名稱:umongo,代碼行數:4,代碼來源:test_motor_asyncio.py

示例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) 
開發者ID:autogestion,項目名稱:pubgate,代碼行數:9,代碼來源:conftest.py

示例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] 
開發者ID:Python3WebSpider,項目名稱:DouYin,代碼行數:12,代碼來源:mongo.py

示例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 
開發者ID:imbolc,項目名稱:aiohttp-login,代碼行數:40,代碼來源:utils.py

示例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.") 
開發者ID:matnad,項目名稱:pollmaster,代碼行數:34,代碼來源:pollmaster.py


注:本文中的motor.motor_asyncio.AsyncIOMotorClient方法示例由純淨天空整理自Github/MSDocs等開源代碼及文檔管理平台,相關代碼片段篩選自各路編程大神貢獻的開源項目,源碼版權歸原作者所有,傳播和使用請參考對應項目的License;未經允許,請勿轉載。