How to use the motor.motor_asyncio function in motor

To help you get started, we’ve selected a few motor examples, based on popular ways it is used in public projects.

Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.

github mongodb / motor / test / asyncio_tests / test_asyncio_basic.py View on Github external
def test_underscore(self):
        self.assertIsInstance(self.cx['_db'],
                              motor_asyncio.AsyncIOMotorDatabase)
        self.assertIsInstance(self.db['_collection'],
                              motor_asyncio.AsyncIOMotorCollection)
        self.assertIsInstance(self.collection['_collection'],
                              motor_asyncio.AsyncIOMotorCollection)

        with self.assertRaises(AttributeError):
            self.cx._db

        with self.assertRaises(AttributeError):
            self.db._collection

        with self.assertRaises(AttributeError):
            self.collection._collection
github virtool / virtool / virtool / app.py View on Github external
async def init_db(app):
    """
    An application ``on_startup`` callback that attaches an instance of :class:`~AsyncIOMotorClient` and the ``db_name``
    to the Virtool ``app`` object. Also initializes collection indices.

    :param app: the app object
    :type app: :class:`aiohttp.web.Application`

    """
    if app["setup"] is None:
        settings = app["settings"]

        db_client = motor_asyncio.AsyncIOMotorClient(
            settings["db_connection_string"],
            serverSelectionTimeoutMS=6000
        )

        try:
            await db_client.list_database_names()
        except pymongo.errors.ServerSelectionTimeoutError:
            logger.critical("Could not connect to MongoDB server")
            sys.exit(1)

        app["db"] = virtool.db.core.DB(
            db_client[settings["db_name"]],
            app["dispatcher"].dispatch
        )
github stacy0416 / afs2-datasource / afs2datasource / apmDSHelper.py View on Github external
async def connect(self):
    if self._connection is None:
      if self._db_type == const.DB_TYPE['MONGODB']:
        self._connection = motor.motor_asyncio.AsyncIOMotorClient(self._mongo_url)
        data = await self._connection.server_info()
        self._db = self._mongo_url.split('/')[-1]
      self._token = self._get_token()
github bmoscon / cryptofeed / cryptofeed / backends / mongo.py View on Github external
def __init__(self, db, host='127.0.0.1', port=27017, key=None, numeric_type=str, **kwargs):
        self.conn = motor.motor_asyncio.AsyncIOMotorClient(host, port)
        self.db = self.conn[db]
        self.numeric_type = numeric_type
        self.collection = key if key else self.default_key
github fzxiao233 / live_monitor_server / src / tools.py View on Github external
def __init__(self, db: str):
        client = motor.motor_asyncio.AsyncIOMotorClient('mongodb://127.0.0.1:27017')
        _db = client["Video"]
        self.db = _db[db]
        self.logger = logging.getLogger('run.db')
github frankie567 / fastapi-users / src / full_mongodb.py View on Github external
import motor.motor_asyncio
from fastapi import FastAPI
from fastapi_users import BaseUser, FastAPIUsers
from fastapi_users.authentication import JWTAuthentication
from fastapi_users.db import MongoDBUserDatabase

DATABASE_URL = "mongodb://localhost:27017"
SECRET = "SECRET"


client = motor.motor_asyncio.AsyncIOMotorClient(DATABASE_URL)
db = client["database_name"]
collection = db["users"]


user_db = MongoDBUserDatabase(collection)


class User(BaseUser):
    pass


auth_backends = [
    JWTAuthentication(secret=SECRET, lifetime_seconds=3600),
]

app = FastAPI()
github ekonda / sketal / plugins / technical / storage.py View on Github external
except ValueError:
                    import traceback
                    traceback.print_exc()

                    print("Storage :: File `" + path + "` is broken.")

                except FileNotFoundError:
                    pass

        else:
            if save_to_file:
                raise AttributeError("You can't use `save_to_file` with "
                    "`in_memory` equals to False")

            self.client = motor.motor_asyncio.AsyncIOMotorClient(host, port)

            self.database = self.client[database]

            self.users = self.database["users"]
            self.chats = self.database["chats"]
            self.meta = self.database["meta"]

        self.cached_meta = None

        self.in_memory = in_memory
        self.save_to_file = save_to_file
github virtool / virtool / virtool / app.py View on Github external
if settings.get("db_use_auth", False):
        db_username = quote_plus(settings["db_username"])
        db_password = quote_plus(settings["db_password"])

        auth_string = "{}:{}@".format(db_username, db_password)

    ssl_string = ""

    if settings.get("db_use_ssl", False):
        ssl_string += "?ssl=true"

    string = "mongodb://{}{}:{}/{}{}".format(auth_string, db_host, db_port, app["db_name"], ssl_string)

    app["db_connection_string"] = string

    db_client = motor_asyncio.AsyncIOMotorClient(
        string,
        serverSelectionTimeoutMS=6000,
        io_loop=app.loop
    )

    try:
        await db_client.database_names()
    except pymongo.errors.ServerSelectionTimeoutError:
        raise virtool.errors.MongoConnectionError(
            "Could not connect to MongoDB server at {}:{}".format(db_host, db_port)
        )

    app["db"] = virtool.db.iface.DB(db_client[app["db_name"]], app["dispatcher"].dispatch, app.loop)

    await app["db"].connect()
github avrae / avrae / migrators / hb_sub_reindexing.py View on Github external
async def run():
    mdb = None
    if 'test' in sys.argv:
        import credentials

        mdb = motor.motor_asyncio.AsyncIOMotorClient(credentials.test_mongo_url).avrae
    else:
        mclient = motor.motor_asyncio.AsyncIOMotorClient(os.getenv('MONGO_URL', "mongodb://localhost:27017"))
        mdb = mclient[os.getenv('MONGO_DB', "avrae")]

    if 'bestiary' in sys.argv:
        input(f"Reindexing {mdb.name} bestiaries. Press enter to continue.")
        await migrate_bestiaries(mdb)
github zpoint / idataapi-transform / idataapi_transform / DataProcess / Config / ConfigUtil / WriterConfig.py View on Github external
def get_mongo_cli(self):
        if self.client is None:
            kwargs = {
                "host": self.host,
                "port": self.port
            }
            if self.username:
                self.client = motor.motor_asyncio.AsyncIOMotorClient(
                    "mongodb://%s:%s@%s:%s/%s" % (self.username, self.password, kwargs["host"],
                                                  str(kwargs["port"]), self.database))
            else:
                self.client = motor.motor_asyncio.AsyncIOMotorClient(**kwargs)
            self.collection_cli = self.client[self.database][self.collection]
        return self.client