async def get_orders_for_courier( cls, session: AsyncSession, courier_id: int) -> Tuple[str, List["Order"]]: courier = await Courier.get_courier(courier_id=courier_id, session=session) if courier is None: raise web.HTTPBadRequest if not courier.regions or not courier.working_hours: return "", [] orders = await session.execute( select(Order).filter( and_( Order.region.in_(courier.regions), not_(Order.completed), Order.weight <= courier.get_capacity(), is_(Order.courier_id, None), )).order_by(Order.weight)) good_orders = [] orders_sum_weight = 0 if courier.orders: return courier.orders[0].assign_time, courier.orders raw_orders = get_best_orders( [raw_order[0] for raw_order in orders.fetchall()], capacity=courier.get_capacity(), ) assign_time = ( datetime.datetime.utcnow().isoformat(timespec="milliseconds") + "Z") for order in raw_orders: for order_timedelta in order.delivery_hours_timedeltas: for courier_timedelta in courier.working_hours_timedeltas: if (check_courier_can_delivery_by_time( order_timedelta=order_timedelta, courier_timedelta=courier_timedelta, ) and (order not in good_orders) and (round(orders_sum_weight + order.weight, 2) <= courier.get_capacity())): orders_sum_weight = round( orders_sum_weight + order.weight, 2) order.cost = 500 * courier.get_coefficient() order.courier_id = courier.id order.assign_time = assign_time good_orders.append(order) if not good_orders: return assign_time, [] session.add_all(good_orders) await session.commit() return assign_time, good_orders
async def async_create(cls, db_session: AsyncSession, db_commit=False, **data): instance = cls(**data) # noqa db_session.add_all([instance]) await db_session.flush() if db_commit: await db_session.commit() return instance
async def wikis(db: AsyncSession) -> List[Wiki]: db.add_all([ Wiki(id=uuid.uuid4(), slug="my_wiki"), Wiki(id=uuid.uuid4(), slug="your_wiki"), ]) await db.commit() wikis = await db.execute( select(Wiki).where(Wiki.slug.in_({"my_wiki", "your_wiki"})).order_by("slug")) return wikis.scalars().all()
async def pages(db: AsyncSession, wikis: List[Wiki]) -> List[Page]: wiki = wikis[0] pages = [ Page(wiki_id=wiki.id, id=uuid.uuid4(), slug="page_1", title="Page One"), Page(wiki_id=wiki.id, id=uuid.uuid4(), slug="page_2", title="Page Two"), ] db.add_all(pages) await db.commit() await db.refresh(pages[0]) await db.refresh(pages[1]) return pages
async def create_multi_stuff(payload: list[StuffSchema], db_session: AsyncSession = Depends(get_db)): try: stuff_instances = [ Stuff(name=stuf.name, description=stuf.description) for stuf in payload ] db_session.add_all(stuff_instances) await db_session.commit() except SQLAlchemyError as ex: # logger.exception(ex) raise HTTPException(status_code=status.HTTP_422_UNPROCESSABLE_ENTITY, detail=repr(ex)) else: logger.info( f"{len(stuff_instances)} instances of Stuff inserted into database." ) return True
async def create( cls: T, session: AsyncSession, json_data: dict, id_key: str, ) -> Tuple[Optional[List[Union[T, int]]], Optional[List[int]]]: elements = cls.get_items_list_from_json(json_data=json_data, id_key=id_key) old_ids = await cls.find_duplicates( session=session, elements=elements, ) if old_ids: return None, old_ids session.add_all(elements) await session.commit() return elements, None
async def save_data_to_db(session: AsyncSession, json_users_data: list, json_posts_data: list): logger.info("Enter module save_data_to_db") users = [ User(id=item["id"], name=item["name"], username=item["username"], email=item["email"]) for item in json_users_data ] session.add_all(users) posts = [ Post(id=item["id"], title=item["title"], body=item["body"], user_id=item["userId"]) for item in json_posts_data ] session.add_all(posts) await session.commit()