示例#1
0
    async def test_connection_failure(self):
        # Assuming there isn't anything actually running on this port
        client = motor_asyncio.AsyncIOMotorClient("localhost",
                                                  8765,
                                                  serverSelectionTimeoutMS=10,
                                                  io_loop=self.loop)

        with self.assertRaises(ConnectionFailure):
            await client.admin.command("ismaster")
示例#2
0
    def asyncio_rsc(self, uri=None, *args, **kwargs):
        """Get an open MotorClient for replica set.

        Ignores self.ssl, you must pass 'ssl' argument.
        """
        return motor_asyncio.AsyncIOMotorClient(
            uri or env.rs_uri,
            *args,
            **self.get_client_kwargs(**kwargs))
示例#3
0
    def asyncio_client(self, uri=None, *args, **kwargs):
        """Get an AsyncIOMotorClient.

        Ignores self.ssl, you must pass 'ssl' argument.
        """
        return motor_asyncio.AsyncIOMotorClient(uri or env.uri,
                                                *args,
                                                io_loop=self.loop,
                                                **kwargs)
示例#4
0
async def init_mongo(conf, loop):
    host = os.environ.get('DOCKER_MACHINE_IP', '127.0.0.1')
    conf['host'] = host
    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]
示例#5
0
    def __init__(self):
        client = motor_asyncio.AsyncIOMotorClient(
            host='mongodb://localhost:33333'
        )
        db = client.db

        self.users = db.users
        self.tasks = db.tasks
        self.proposed_tasks = db.proposed_tasks
示例#6
0
    async def init_async(config):
        import motor.motor_asyncio as aiomotor

        conn = aiomotor.AsyncIOMotorClient(
            config["connection_string"],
            ssl_ca_certs="../additional/YandexInternalRootCA.crt",
            ssl_cert_reqs=ssl.CERT_REQUIRED)
        db = conn[config["db"]]
        return db
    def test_connection_failure(self):
        # Assuming there isn't anything actually running on this port.
        client = motor_asyncio.AsyncIOMotorClient('localhost:8765',
                                                  replicaSet='rs',
                                                  io_loop=self.loop,
                                                  serverSelectionTimeoutMS=10)

        with self.assertRaises(pymongo.errors.ConnectionFailure):
            yield from client.admin.command('ismaster')
    def test_connect(self):
        client = motor_asyncio.AsyncIOMotorClient('%s:%s' %
                                                  (env.host, env.port),
                                                  replicaSet='anything',
                                                  serverSelectionTimeoutMS=10,
                                                  io_loop=self.loop)

        with self.assertRaises(pymongo.errors.ServerSelectionTimeoutError):
            yield from client.test.test.find_one()
示例#9
0
def async_db(db_name):
    db_uri = "mongodb://{username}:{password}@{host}:{port}".format(
        username=quote_plus(os.getenv("DB_USERNAME", "root")),
        password=quote_plus(os.getenv("DB_PASSWORD", "root")),
        host=quote_plus(os.getenv("DB_HOST", "localhost")),
        port=quote_plus(os.getenv("DB_PORT", "27017")),
    )
    db_client = motor_asyncio.AsyncIOMotorClient(db_uri)
    return db_client[db_name]
示例#10
0
 def __init__(self, **kwargs):
     super().__init__(description=kwargs.pop("description"),
                      command_prefix=self.__get_prefix,
                      activity=kwargs.pop("activity"))
     self.config = Config.fromJSON("config.json")
     self.motorClient = motor_asyncio.AsyncIOMotorClient(
         self.config.mongo['URI'],
         serverSelectionTimeoutMS=self.config.mongo['timeout'])
     self.mongoIO = mongoIO(self)
示例#11
0
def setup_mongo(app: FastAPI):
    app.client = ma.AsyncIOMotorClient(MONGO_HOST)
    app.db = app.client[MONGO_DB_NAME]

    app.mongo = {
        'beer': Beer(app.db),
        'wine': Wine(app.db),
        'vodka': Vodka(app.db)
    }
示例#12
0
async def main():
    client = ma.AsyncIOMotorClient(MONGO_HOST)
    db = client[MONGO_DB_NAME]

    for month in MONTHS:
        yearmonth = "%s%02d" % (YEAR, month)

        game_list = []
        game_counter = 0
        failed = 0
        cursor = None

        print("---", yearmonth[:4], yearmonth[4:])
        filter_cond = {
            "$and": [
                {
                    "$expr": {
                        "$eq": [{
                            "$year": "$d"
                        }, int(yearmonth[:4])]
                    }
                },
                {
                    "$expr": {
                        "$eq": [{
                            "$month": "$d"
                        }, int(yearmonth[4:])]
                    }
                },
            ]
        }
        cursor = db.game.find(filter_cond)

        if cursor is not None:
            async for doc in cursor:
                try:
                    # print(game_counter)
                    # log.info("%s %s %s" % (doc["d"].strftime("%Y.%m.%d"), doc["_id"], C2V[doc["v"]]))
                    pgn_text = pgn(doc)
                    if pgn_text is not None:
                        game_list.append(pgn_text)
                    game_counter += 1
                except Exception:
                    failed += 1
                    log.error(
                        "Failed to load game %s %s %s (early games may contain invalid moves)",
                        doc["_id"],
                        C2V[doc["v"]],
                        doc["d"].strftime("%Y.%m.%d"),
                    )
                    continue
            print("failed/all:", failed, game_counter)
        pgn_text = "\n".join(game_list)

        with bz2.open(yearmonth + ".pgn", "wt") as f:
            f.write(pgn_text)
示例#13
0
 def __init__(self, settings):
     super().__init__(command_prefix=_get_prefix)
     os.chdir(self.base_directory)
     self.settings = settings
     self.extension_file = os.path.join(self.base_directory,
                                        'extensions.json')
     self.start_time = time.time()
     if self.settings['release'] == 'production':
         self.db: motor.AsyncIOMotorDatabase = motor.AsyncIOMotorClient(
         ).NRus
     elif self.settings['release'] == 'devel':
         self.db: motor.AsyncIOMotorCollection = motor.AsyncIOMotorClient(
         ).NRusTesting
     else:
         raise ValueError('Invalid value for `release` in `settings.json`')
     self.guild_settings: motor.AsyncIOMotorCollection = self.db.guilds
     self.guild_prefixes: dict = {}
     self.indexed: list = []
     self.load_extensions()
示例#14
0
文件: base.py 项目: Choco02/Nixest
 def __init__(self, *, name, uri, bot):
     """
      - Funções:
       self.connection : Fazer a conexão com o banco de dados mongoDB através do Motor asyncio.
       self.db : Puxa informações da 'collection'.
     """
     self.roxanne = bot
     self.connection = motor_asyncio.AsyncIOMotorClient(uri)
     self.db = db = self.connection[name]
     self.guilds = db.guilds
示例#15
0
    async def test_connect(self):
        client = motor_asyncio.AsyncIOMotorClient(
            "%s:%s" % (env.host, env.port),
            replicaSet="anything",
            serverSelectionTimeoutMS=10,
            io_loop=self.loop,
        )

        with self.assertRaises(pymongo.errors.ServerSelectionTimeoutError):
            await client.test.test.find_one()
示例#16
0
    async def get_articles_by(request):
        token = request.match_info['token']
        db = motor.AsyncIOMotorClient(MONGO_PATH.format(token, token)).db

        try:
            query = await request.json()
        except:
            raise web.HTTPBadRequest()

        return await get_articles_query(db, token, query)
示例#17
0
async def querysteamid(session: nonebot.CommandSession):
    accinfo = session.get('accinfo', prompt='请输入steam64位id')
    client = amongo.AsyncIOMotorClient(mongolink)
    usercollection = client['steamdb']['user']
    match_res = await usercollection.find_one({'steamid64':accinfo})
    if not match_res:
        await session.send(await deal_accinfo(accinfo))
    else:
        word_back = await send_userinfo(steamid64=accinfo)
        await session.send(word_back)
示例#18
0
    def test_connection_timeout(self):
        # Motor merely tries to time out a connection attempt within the
        # specified duration; DNS lookup in particular isn't charged against
        # the timeout. So don't measure how long this takes.
        client = motor_asyncio.AsyncIOMotorClient(
            'example.com', port=12345,
            serverSelectionTimeoutMS=1, io_loop=self.loop)

        with self.assertRaises(ConnectionFailure):
            yield from client.admin.command('ismaster')
示例#19
0
 def __init__(self, *, name, uri, bot):
     self.disco = bot
     self._client = motor_asyncio.AsyncIOMotorClient(uri)
     self._db = db = self._client[name]
     self._bans = db.bans
     self._guilds = db.guilds
     self._shards = db.shards
     self._mod_logs = db.mod_logs
     self._messages = db.messages
     self._self_assignable_roles = db.self_assignable_roles
示例#20
0
async def main():
    client = ma.AsyncIOMotorClient(MONGO_HOST)
    db = client[MONGO_DB_NAME]

    # Not 100% accurate hack to detect early makpong games saved as chess ("n")
    filter_cond = {
        "$and": [
            {
                "v": "n"
            },
            {
                "d": {
                    "$gt": datetime(2020, 4, 20)
                }
            },
            {
                "$or": [
                    {
                        "$expr": {
                            "$gt": [{
                                "$indexOfBytes": ["$f", "m"]
                            }, -1]
                        }
                    },
                    {
                        "$expr": {
                            "$gt": [{
                                "$indexOfBytes": ["$f", "M"]
                            }, -1]
                        }
                    },
                    {
                        "$expr": {
                            "$gt": [{
                                "$indexOfBytes": ["$f", "s"]
                            }, -1]
                        }
                    },
                    {
                        "$expr": {
                            "$gt": [{
                                "$indexOfBytes": ["$f", "S"]
                            }, -1]
                        }
                    },
                ]
            },
        ]
    }

    cursor = db.game.find(filter_cond)
    async for doc in cursor:
        print(doc["d"], doc["v"], doc["us"], doc["f"])

    await db.game.update_many(filter_cond, {"$set": {"v": "l"}})
示例#21
0
    def new(self, key, **kwargs):
        """Return and register new motor with specified key."""

        client = self._clients.pop(key, None)
        if client:
            client.close()

        client_kwargs = self.kwargs(**kwargs)
        self._clients[key] = client = \
            aiomotor.AsyncIOMotorClient(**client_kwargs)
        return client
示例#22
0
文件: mongo_db.py 项目: dcmq/pydcmq
 def __init__(self, loop):
     self.client = motor_asyncio.AsyncIOMotorClient(io_loop=loop)
     self.db = self.client.test_database
     self.datasets = self.db.datasets
     self.datasets.create_index([("SOPInstanceUID", DESCENDING)],
                                background=True,
                                unique=True)
     self.datasets.create_index([("SeriesInstanceUID", DESCENDING)],
                                background=True)
     self.datasets.create_index([("StudyInstanceUID", DESCENDING)],
                                background=True)
示例#23
0
    def test_timeout(self):
        server = self.server(auto_ismaster=True)
        client = motor_asyncio.AsyncIOMotorClient(server.uri,
                                                  socketTimeoutMS=100,
                                                  io_loop=self.loop)

        with self.assertRaises(pymongo.errors.AutoReconnect) as context:
            yield from client.motor_test.test_collection.find_one()

        self.assertEqual(str(context.exception), 'timed out')
        client.close()
示例#24
0
 def __init__(self, *args, **kwargs):
     super().__init__(*args, **kwargs)
     self.session = aiohttp.ClientSession(loop=self.loop)
     self.process = psutil.Process(os.getpid())
     self.cpu_count = psutil.cpu_count()
     self.process.cpu_percent(None)
     self.start_time = utils.now_time()
     self.loop.create_task(self.load())
     self.block_users = set()
     self.mongo_client = motor_asyncio.AsyncIOMotorClient()
     self.db = self.mongo_client.belphydb
示例#25
0
 async def _connect(self):
     self._conn = motor_asyncio.AsyncIOMotorClient(self.uri,
                                                   io_loop=self.loop)
     try:
         self.connected = await self.wait_db()
     except AutoReconnect as e:
         log.error("Couldn't connect to db %s", self.uri)
         self.connected = await self.wait_db()
     if self.connected:
         self.db = self._conn[self.db_name]
         log.info('Connection Successfully.')
示例#26
0
 def __init__(self, config):
     self.config = config
     self.client = motor_asyncio.AsyncIOMotorClient(self.config['db'])
     self.db = self.client.get_default_database()
     self.event = Event()
     self.user = User(self)
     self.file = Repo(self)
     self.post = Post(self)
     self.settings = Settings(self)
     self.post_categories = PostCategories(self)
     self.related_data_handlers = RelatedDataHandlers(self)
示例#27
0
    def __init__(self):

        # The client in charge of the cluster of databases
        self._database_cluster_client = motor_asyncio.AsyncIOMotorClient(DATABASE_URL, DATABASE_PORT)
        # The database specifically tailored for our discord bot
        self._discord_bot_database = self._database_cluster_client['discord']
        # In this database that we just accessed, we can now use 'collections' which are like folders
        # These 'folders' contain mongo 'documents' which are basically json files that easily translate to
        # Python dictionaries
        self._event_collection = self._discord_bot_database['events']
        self._token_collection = self._discord_bot_database['tokens']
示例#28
0
 def __init__(
     self,
     command_prefix: Optional[Union[str, list[str], Callable]] = None,
     description: str = None,
     **options: Any,
 ):
     self._motor = motor.AsyncIOMotorClient(DB_URI)
     self.db = AIOEngine(self._motor, "discord")
     super().__init__(command_prefix=command_prefix,
                      description=description,
                      **options)
示例#29
0
async def init_data():
    client = aiomotor.AsyncIOMotorClient("mongodb://localhost:27017")
    db = client["product_service"]
    collection_product = db["product"]
    p = {
        "_id": ObjectId(),
        "name": "iphone",
        "desc": "The iPhone is a smartphone made by Apple that combines a computer",
        "parameters": {"size": "10", "brand": "apple"},
    }
    await collection_product.insert_one(p)
示例#30
0
async def init_mongo(app, loop):
    mongo_uri = "mongodb://{}:{}".format(
        app['config']['database']['MONGO_HOST'],
        app['config']['database']['MONGO_PORT'])
    conn = aiomotor.AsyncIOMotorClient(
        mongo_uri,
        maxPoolSize=app['config']['database']['MAX_POOL_SIZE'],
        io_loop=loop)
    db_name = app['config']['database']['MONGO_DB_NAME']

    return conn[db_name]