Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.
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
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
)
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()
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
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')
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()
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
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()
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)
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