def open_connection(): """Opening database client session.""" db.client = AsyncIOMotorClient(settings.MONGODB_URI) db.engine = AIOEngine( motor_client=db.client, database=settings.MONGODB_DB_NAME, )
async def get_all_quotes(client: AsyncIOMotorClient = Depends(get_odm), ): engine = AIOEngine(motor_client=client, database="quotes") quotes = await engine.find(Quote, sort=Quote.id) if quotes: return quotes else: raise HTTPException(status_code=404, detail="No data found!")
async def find_task_id(task_id): client = motor.motor_asyncio.AsyncIOMotorClient(host=settings.MONGO_HOST) engine = AIOEngine(motor_client=client, database='cves') task = await engine.find_one(TaskId, TaskId.task_id == task_id) if task: await engine.delete(task) return True return False
async def get_all_games(client: AsyncIOMotorClient = Depends(get_odm)): engine = AIOEngine(motor_client=client, database="backlogs") data = [ game async for game in engine.find(BacklogGame, sort=BacklogGame.id) ] if data: return data else: raise HTTPException(status_code=404, detail="No data found!")
async def add_quotes( doc_list: List[Quote], client: AsyncIOMotorClient = Depends(get_odm), ): engine = AIOEngine(motor_client=client, database="quotes") result = await engine.save_all(doc_list) return { "result": result, }
async def add_games( doc_list: List[BacklogGame], client: AsyncIOMotorClient = Depends(get_odm), user: UserOut = Depends(oauth2_scheme), ): engine = AIOEngine(motor_client=client, database="backlogs") result = await engine.save_all(doc_list) return { "result": result, }
async def setup(cls, app): """Setup models. On an http model this implies creating an aiohttp clientsession that will be used later on (see `send_action`) """ cfg = app['application'].env if cfg('MONGODB', None): client = AsyncIOMotorClient(cfg('MONGODB')) app['mongodb'] = AIOEngine(motor_client=client)
async def get_quote( oid: ObjectId, client: AsyncIOMotorClient = Depends(get_odm), ): engine = AIOEngine(motor_client=client, database="quotes") quote = await engine.find_one(Quote, Quote.id == oid) if quote: return quote else: raise HTTPException(status_code=404, detail="No data found!")
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)
async def get_game( oid: ObjectId, client: AsyncIOMotorClient = Depends(get_odm), user: UserOut = Depends(oauth2_scheme), ): engine = AIOEngine(motor_client=client, database="backlogs") game = await engine.find_one(BacklogGame, BacklogGame.id == oid) if game: return game else: raise HTTPException(status_code=404, detail="No data found!")
async def create_ingredients_from_csv(): ingredients = pandas.read_csv('ingredients.csv', header=None) print(ingredients[0].tolist()) models = [] for ingredient_name in ingredients[0].tolist(): models.append(Ingredient(name=ingredient_name)) motor = AsyncIOMotorClient(host="209.159.204.189", port=5433) engine = AIOEngine(motor_client=motor, database="Recipe") await engine.save_all(models)
async def random_quote(client: AsyncIOMotorClient = Depends(get_odm)): engine = AIOEngine(motor_client=client, database="quotes") collection = engine.get_collection(Quote) # random sample quote = await collection.aggregate([{ '$sample': { 'size': 1 } }]).to_list(length=1) # convert aggregation list to Quote class quote = Quote( quote_text=quote[0]['quote_text'], quote_origin=quote[0]['quote_origin'], ) return quote
async def count_by_status(client: AsyncIOMotorClient = Depends(get_odm)): engine = AIOEngine(motor_client=client, database="backlogs") collection = engine.get_collection(BacklogGame) results = await collection.aggregate([{ '$group': { '_id': '$game_status', 'count': { '$sum': 1 } } }]).to_list(length=None) stats = {result.get('_id'): result.get('count') for result in results} sorted_stats = dict( sorted(stats.items(), key=lambda item: item[1], reverse=True)) return sorted_stats
async def edit_quote( oid: ObjectId, patch: QuotePatch, client: AsyncIOMotorClient = Depends(get_odm), ): engine = AIOEngine(motor_client=client, database="quotes") quote = await engine.find_one(Quote, Quote.id == oid) if quote is None: raise HTTPException(status_code=404, detail="No data found!") patch_dict = patch.dict(exclude_unset=True) for attr, value in patch_dict.items(): setattr(quote, attr, value) result = await engine.save(quote) return { "result": result, }
async def edit_game( oid: ObjectId, patch: BacklogGamePatch, client: AsyncIOMotorClient = Depends(get_odm), user: UserOut = Depends(oauth2_scheme), ): engine = AIOEngine(motor_client=client, database="backlogs") game = await engine.find_one(BacklogGamePatch, BacklogGamePatch.id == oid) if game is None: raise HTTPException(status_code=404, detail="No data found!") patch_dict = patch.dict(exclude_unset=True) for attr, value in patch_dict.items(): setattr(game, attr, value) result = await engine.save(game) return { "result": result, }
async def search( client: AsyncIOMotorClient = Depends(get_odm), dlc: YesNo = None, now_playing: YesNo = None, game_status: GameStatus = None, q: str = None, ): engine = AIOEngine(motor_client=client, database="backlogs") initial_args = { 'dlc': dlc, 'now_playing': now_playing, 'game_status': game_status, } final_args = {k: v for k, v in initial_args.items() if v is not None} if final_args: query_expression_list = [(getattr(BacklogGame, key)) == value for key, value in final_args.items()] combined_query_expression = query.and_(*query_expression_list) else: combined_query_expression = False # change to plain q for OR results. f"\"{q}\"" is an AND search. if combined_query_expression: results = await engine.find( BacklogGame, combined_query_expression, sort=(BacklogGame.dlc, BacklogGame.id), ) elif q == '' or q is None: results = await engine.find( BacklogGame, sort=(BacklogGame.dlc, BacklogGame.id), ) else: results = await engine.find( BacklogGame, {'$text': { '$search': f"\"{q}\"" }}, sort=(BacklogGame.dlc, BacklogGame.id), ) return results
async def playtime(client: AsyncIOMotorClient = Depends(get_odm)): engine = AIOEngine(motor_client=client, database="backlogs") collection = engine.get_collection(BacklogGame) results = await collection.aggregate([{ '$group': { '_id': None, 'total_hours': { '$sum': '$game_hours' }, 'total_minutes': { '$sum': '$game_minutes' } } }]).to_list(length=None) # move chunks of 60 minutes into the hours count leftover_minutes = results[0].get('total_minutes') % 60 hours_to_move = (results[0].get('total_minutes') - leftover_minutes) / 60 results[0]['total_hours'] = int(results[0]['total_hours'] + hours_to_move) results[0]['total_minutes'] = int(leftover_minutes) return results[0]
from odmantic import AIOEngine, EmbeddedModel, Model class CapitalCity(EmbeddedModel): name: str population: int class Country(Model): name: str currency: str capital_city: CapitalCity countries = [ Country( name="Switzerland", currency="Swiss franc", capital_city=CapitalCity(name="Bern", population=1035000), ), Country( name="Sweden", currency="Swedish krona", capital_city=CapitalCity(name="Stockholm", population=975904), ), ] engine = AIOEngine() await engine.save_all(countries)
from app.config import MONGO_URL from motor.motor_asyncio import AsyncIOMotorClient from odmantic import AIOEngine client = AsyncIOMotorClient(MONGO_URL) db = AIOEngine(motor_client=client, database="syskaoh")
from motor.motor_asyncio import AsyncIOMotorClient from odmantic import AIOEngine client = AsyncIOMotorClient("mongodb://localhost:27017/") engine = AIOEngine(motor_client=client, database="example_db")
from typing import List import uvicorn from fastapi import FastAPI from motor.motor_asyncio import AsyncIOMotorClient from odmantic import AIOEngine from models import Ingredient, Recipe app = FastAPI() motor = AsyncIOMotorClient(host="209.159.204.189", port=5433) engine = AIOEngine(motor_client=motor, database="Recipe") @app.get("/ingredient/", response_model=List[Ingredient]) async def get_ingredients(): results = await engine.find(Ingredient) return results @app.get("/recipe/", response_model=List[Recipe]) async def get_recipes(): results = await engine.find(Recipe) return results if __name__ == "__main__": uvicorn.run("app:app", host="0.0.0.0", port=8000, log_level="info") """ @app.put("/trees/", response_model=Tree) async def create_tree(tree: Tree):
telethn = TelegramClient("CUTIEPII", API_ID, API_HASH) dispatcher = updater.dispatcher print("[CUTIEPII]: PYROGRAM CLIENT STARTING") session_name = TOKEN.split(":")[0] pgram = Client( session_name, api_id=API_ID, api_hash=API_HASH, bot_token=TOKEN, ) print( "[CUTIEPII]: Connecting To Yūki • Data Center • Mumbai • MongoDB Database") mongodb = MongoClient(MONGO_DB_URL, MONGO_PORT)[MONGO_DB] motor = motor_asyncio.AsyncIOMotorClient(MONGO_DB_URL) db = motor[MONGO_DB] engine = AIOEngine(motor, MONGO_DB) print("[INFO]: INITIALZING AIOHTTP SESSION") aiohttpsession = ClientSession() # ARQ Client print("[INFO]: INITIALIZING ARQ CLIENT") arq = ARQ(ARQ_API_URL, ARQ_API_KEY, aiohttpsession) print( "[CUTIEPII]: Connecting To Yūki • Data Center • Mumbai • PostgreSQL Database" ) ubot = TelegramClient(StringSession(STRING_SESSION), APP_ID, APP_HASH) print( "[CUTIEPII]: Connecting To Yūki • Cutiepii Userbot (t.me/Awesome_Cutiepii)" ) timeout = httpx.Timeout(40, pool=None) http = httpx.AsyncClient(http2=True, timeout=timeout)
class Food(Model, ABC): name: str expire_days: int = Field(ge=0) created: int active: bool food_type: Optional[str] freezer: Optional[bool] = False pantry: Optional[bool] = False shopping_list: Optional[bool] = False app = FastAPI() motor = AsyncIOMotorClient(host=DATABASE_URL, port=DATABASE_PORT) engine = AIOEngine(motor_client=motor, database=DATABASE_NAME) @app.get("/food/", response_model=List[Food]) async def get_all_food(active: bool = False): if active: results = await engine.find(Food, Food.active == True, sort=Food.expire_days) else: results = await engine.find(Food, sort=Food.expire_days) return results @app.get("/shopping/", response_model=List[Food]) async def get_shopping_list(): results = await engine.find(Food, Food.shopping_list == True, sort=Food.expire_days)
def __init__(self, url, name): client = AsyncIOMotorClient(url) self.engine = AIOEngine(motor_client=client, database=name)
async def make_instances(): motor = AsyncIOMotorClient(host=DATABASE_URL, port=DATABASE_PORT) engine = AIOEngine(motor_client=motor, database=DATABASE_NAME) await engine.save_all(instances) results = await engine.find(Food) pprint(results)
async def get_instances(): motor = AsyncIOMotorClient(host="209.159.204.189", port=5433) engine = AIOEngine(motor_client=motor, database="Recipe") results = await engine.find(Recipe, Recipe.owner == 'tim') pprint(results)
import betterlogging as bl from aiogram import Bot, Dispatcher, types from aiogram.contrib.fsm_storage.redis import RedisStorage2 from motor.core import AgnosticCollection from motor.motor_asyncio import AsyncIOMotorClient from odmantic import AIOEngine from .config import config bl.basic_colorized_config(level=bl.INFO) logger = bl.getLogger('zmanim_bot') storage = RedisStorage2(host=config.REDIS_HOST, port=config.REDIS_PORT, db=config.REDIS_DB) bot = Bot(config.BOT_TOKEN, parse_mode=types.ParseMode.HTML) dp = Dispatcher(bot, storage=storage) loop = bot.loop motor_client = AsyncIOMotorClient(config.DB_URL) collection: AgnosticCollection = motor_client[config.DB_NAME][config.DB_COLLECTION_NAME] db_engine = AIOEngine(motor_client, database=config.DB_NAME)
from motor.motor_asyncio import AsyncIOMotorClient from odmantic import AIOEngine from config import settings import os MONGO_USERNAME = settings.MONGO_USERNAME MONGO_PASSWORD = settings.MONGO_PASSWORD MONGO_HOST = settings.MONGO_HOST MONGO_DATABASE = settings.MONGO_DATABASE # Cliente Motor que se conecta con la base de datos Mongo client = AsyncIOMotorClient( f"mongodb://{MONGO_USERNAME}:{MONGO_PASSWORD}@{MONGO_HOST}:27017/") # Engine de Odmantic que sirve como ODM conectado a la base de datos engine = AIOEngine(motor_client=client, database=settings.MONGO_DATABASE)
async def start_db(): global db db.client = AsyncIOMotorClient(MONGO_URL) db.motor = AIOEngine(motor_client=db.client, database="syskaoh") db.fs = asmotor.AsyncIOMotorGridFSBucket(db.client.images) print("db connexion established")
from motor.motor_asyncio import AsyncIOMotorClient from odmantic import AIOEngine from app.mongo import settings client = AsyncIOMotorClient(settings.mongodb_uri) engine = AIOEngine(motor_client=client, database=settings.db)