async def execute(self, params=None): config = ioc.instance(ioc.Dependencies.config) client = ioc.instance(ioc.Dependencies.mongodb_driver) self.db = client[config.mongodb.database] with open(f"{FIXTURES_PATH}/products.json") as f: documents = json.load(f) for document in documents: product = schemas.PRODUCT_SCHEMA.load(document) await self.db.products.insert_one(document) product["id"] = str(document.pop("_id")) self.products.append(product) with open(f"{FIXTURES_PATH}/users.json") as f: documents = json.load(f) documents[1]["dateOfBirth"] = datetime.now().isoformat() for document in documents: document["dateOfBirth"] = datetime.fromisoformat( document["dateOfBirth"]) user = schemas.USER_SCHEMA.load(document) await self.db.users.insert_one(document) user["id"] = str(document.pop("_id")) self.users.append(user)
def __init__(self): config = ioc.instance(ioc.Dependencies.config) client = ioc.instance(ioc.Dependencies.mongodb_driver) database = client[config.mongodb.database] if not self.collection_name: raise NotImplementedError("The collection name wasn't set") self.collection: Collection = database[self.collection_name] super().__init__()
async def calculate(self, product): logger.info("Calculating discount") calculator = ioc.instance(ioc.Dependencies.discounts_api) request = CalculateRequest() request.user_id = self.user.id request.product_id = product.id try: resp: CalculateResponse = await calculator.Calculate(request) except AioRpcError as ex: if ex.code() == StatusCode.NOT_FOUND: raise errors.NotFound(ex.details()) raise discount = resp.product.discount if discount and discount.percentage > 0: return Discount(percentage=discount.percentage, value_in_cents=discount.value_in_cents)
async def list(self, user_id, filters): logger.info(f"Listing products by filters {filters}") request = dict( contracts.ListProductsRequest(user_id=user_id, **filters)) user = domain.User(id=user_id) calculator = domain.DiscountCalculator(user=user) repo = ioc.instance(ioc.Dependencies.product_repo) products = await repo.list(request) async def calculate_discount(product): try: product.discount = await calculator.calculate(product) except errors.BaseError: raise except Exception as ex: logger.warning( f"Failed calculating discount for product {product.id}: {ex}" ) await asyncio.gather(*[calculate_discount(pr) for pr in products]) return contracts.ListProductsResponse(data=products, **request)
async def list_products(request: Request, user_id): svc = ioc.instance(ioc.Dependencies.product_svc) result = await svc.list(user_id, dict(request.query_args)) return json(result.dict())