async def register(*, session: AsyncSession = Depends(get_session), request: Request, user_in: api_models.UserIn, background_tasks: BackgroundTasks): user_select_query = select(db_models.User).filter( or_(db_models.User.username == user_in.username, db_models.User.email == user_in.email)) result = await session.execute(user_select_query) db_user = result.scalar() if db_user is not None: raise HTTPException(409, "User already exists") user = db_models.User(username=user_in.username, email=user_in.email, hashed_password=PASSWORD_CONTEXT.hash( user_in.password), email_confirmed=not settings.EMAILS_ON) session.add(user) await session.commit() if settings.EMAILS_ON: confirm_jwt = create_jwt_from_data({"sub": user.email}) confirm_url = str(request.base_url) + f"api/confirm/{confirm_jwt}" background_tasks.add_task(send_email_confirmation, user.email, confirm_url) return Response(status_code=201)
async def reset_password( token: str = Body(...), new_password: str = Body(...), db: AsyncSession = Depends(deps.get_db), ) -> Any: """ Reset password """ email = verify_token(token) if not email: raise HTTPException(status_code=400, detail="Invalid token") user = await crud.user.get_by_key(db, key="email", value=email) if not user: raise HTTPException( status_code=404, detail="The user with this username does not exist in the system.", ) elif not crud.user.is_active(user[0]): raise HTTPException(status_code=400, detail="Inactive user") else: user = user[0] hashed_password = get_password_hash(new_password) user.hashed_password = hashed_password db.add(user) await db.commit() return {"msg": "Password updated successfully"}
async def update( primary_key: int, fields: CannedResponseUpdate, db: AsyncSession = Depends(get_db) ): # Get the response response = await db.get(CannedResponse, primary_key) if response is None: raise HTTPException(status_code=404, detail="not found") # Set fields if fields.key is not None: response.key = fields.key if fields.title is not None: response.title = fields.title if fields.content is not None: response.content = fields.content if fields.fields is not None: response.fields = fields.fields # Commit the changes try: db.add(response) await db.commit() except IntegrityError: raise HTTPException(status_code=409, detail="field 'key' must be unique") return response
def test_init(self, async_engine): ss = AsyncSession(bind=async_engine) is_(ss.bind, async_engine) binds = {Table: async_engine} ss = AsyncSession(binds=binds) is_(ss.binds, binds)
async def create(self, db: AsyncSession, *, obj_in: CreateSchemaType) -> ModelType: obj_in_data = jsonable_encoder(obj_in) db_obj = self.model(**obj_in_data) # type: ignore db.add(db_obj) await db.commit() await db.refresh(db_obj) return db_obj
async def test_join_to_external_transaction(self, async_engine): User = self.classes.User async with async_engine.connect() as conn: t1 = await conn.begin() async_session = AsyncSession(conn) aconn = await async_session.connection() eq_(aconn.get_transaction(), t1) eq_(aconn, conn) is_(aconn.sync_connection, conn.sync_connection) u1 = User(id=1, name="u1") async_session.add(u1) await async_session.commit() assert conn.in_transaction() await conn.rollback() async with AsyncSession(async_engine) as async_session: result = await async_session.execute(select(User)) eq_(result.all(), [])
async def create(self, session: AsyncSession, obj_in: CreateSchemaType) -> ModelType: obj_in_data = dict(obj_in) db_obj = self._model(**obj_in_data) session.add(db_obj) await session.commit() return db_obj
async def add( panel_id: int, fields: ReactionIn, db: AsyncSession = Depends(get_db), ): # Ensure the panel exists panel = await get_panel(db, panel_id) # If the emoji is custom, check that it exists channel = await get_channel(panel.channel_id) emoji = await validate_emoji(channel, fields.emoji) # Add the reaction to the panel try: reaction = Reaction(category_id=fields.category_id, emoji=emoji, panel_id=panel_id) db.add(reaction) await db.commit() except IntegrityError: raise HTTPException(status_code=400, detail="specified category does not exist") # Re-fetch reaction to add the category statement = (select(Reaction).where(Reaction.id == reaction.id).options( selectinload(Reaction.category))) reaction = (await db.execute(statement)).scalars().first() # React with the emoji on the message channel = await get_channel(panel.channel_id) message = await get_message(channel, panel.message_id) if message is not None: await message.add_reaction(emoji) return reaction
async def create_with_owner(self, db: AsyncSession, *, obj_in: ItemCreate, owner_id: int) -> Item: obj_in_data = jsonable_encoder(obj_in) db_obj = self.model(**obj_in_data, owner_id=owner_id) db.add(db_obj) await db.commit() await db.refresh(db_obj) return db_obj
async def create(cls, session: AsyncSession, tg_user: atp.User): db_user = await session.get(cls, tg_user.id) if not db_user: db_user = cls(id=tg_user.id, name=tg_user.full_name) session.add(db_user) logging.info(f"New user {tg_user.full_name}({tg_user.id})") await session.commit() return db_user
async def create_election_candidate(db: AsyncSession, candidate: schema.CandidateBase, election_id: int): db_candidate = model.Candidate(**candidate.dict(), election_id=election_id) db.add(db_candidate) await db.commit() await db.refresh(db_candidate) return db_candidate
async def create_user(db: AsyncSession, request: User): new_user = models.User(name=request.name, email=request.email, password=Hash.encrypt(request.password)) db.add(new_user) await db.commit() await db.refresh(new_user) return ShowUser.from_orm(new_user)
async def add_balances(session: AsyncSession) -> None: stmt = select(User).where(User.discord_id != author_id) result = await session.execute(stmt) for user in result.fetchall(): ordered_parties: list[str] = sorted([author_id, user.discord_id]) session.add( UserBalance(first_party=ordered_parties[0], second_party=ordered_parties[1]))
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 create_card(session: AsyncSession, card: CardInSchema) -> Card: new_card = Card( name=card.name, description=card.description, status=card.status, board_id=card.board_id, ) session.add(new_card) return new_card
async def user(fake, db: AsyncSession) -> User: db.add( User(id=fake.uuid4(), email="*****@*****.**", hashed_password="******")) await db.commit() result = await db.execute( select(User).where(User.email == "*****@*****.**")) return result.scalars().first()
async def crawl(bot, sess: AsyncSession): feeds = (await sess.scalars(select(RSSFeedURL))).all() for feed in feeds: # type: RSSFeedURL data = b"" async with aiohttp.ClientSession() as session: try: async with session.get(feed.url) as res: data = await res.read() except aiohttp.client_exceptions.ClientConnectorError: await bot.say(feed.channel, f"*Error*: `{feed.url}`에 접속할 수 없어요!") continue if not data: await bot.say(feed.channel, f"*Error*: `{feed.url}`에 접속해도 자료를 가져올 수 없어요!") continue f = feedparser.parse(data) if f.bozo != 0: await bot.say(feed.channel, f"*Error*: `{feed.url}`는 올바른 RSS 문서가 아니에요!") continue last_updated = feed.updated_at attachments = [] for entry in reversed(f.entries): t = dateutil.parser.parse(entry.published).astimezone(UTC) if feed.updated_at < t: attachments.append( Attachment( fallback=("RSS Feed: " f"{str(f.feed.title)} - " f"{str(entry.title)} - " f"{entry.links[0].href}"), title=str(entry.title), title_link=entry.links[0].href, text=("\n".join(str( entry.summary).split("\n")[:3]))[:100], author_name=str(f.feed.title), )) last_updated = t feed.updated_at = last_updated if attachments: await bot.api.chat.postMessage( channel=feed.channel, attachments=attachments, as_user=True, ) sess.add(feed) await sess.commit()
async def create_first_user(session: AsyncSession) -> None: email = settings.FIRST_USER_EMAIL password = get_password_hash( settings.FIRST_USER_PASSWORD.get_secret_value()) result = await session.execute(select(User).where(User.email == email)) user: Optional[User] = result.scalars().first() if user is None: session.add( User(email=email, hashed_password=password, is_superuser=True)) await session.commit()
async def remove_feed_channel( cls, session: AsyncSession, guild_id: t.Union[str, int, discord.Guild]) -> None: guild_id = get_datatype_int(guild_id) row = await session.run_sync(lambda session: session.query(cls). filter_by(guild_id=guild_id).first()) await session.run_sync(lambda session: session.delete(row)) await session.commit()
async def create(self, db: AsyncSession, *, obj_in: UserCreate) -> User: db_obj = User( email=obj_in.email, hashed_password=get_password_hash(obj_in.password), full_name=obj_in.full_name, ) db.add(db_obj) await db.commit() await db.refresh(db_obj) return db_obj
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 create(session: AsyncSession = Depends(async_session)): assert not await get_widget(session) widget = Widget(name="Calendar") session.add(widget) await session.commit() widget = await get_widget(session) assert widget return {"message": f"Created the {widget.name} widget!"}
async def create(response: CannedResponseIn, db: AsyncSession = Depends(get_db)): try: # Extract the fields r = CannedResponse(**response.dict()) # Add it to the database async with db.begin(): db.add(r) return r except IntegrityError: raise HTTPException(status_code=409, detail="field 'key' must be unique")
async def urls_post( *, session: AsyncSession = Depends(get_session), user: api_models.User = Depends(current_active_user), url: api_models.UrlIn = Depends(is_valid_url), ): owner = await fetch_user(user.username, session) db_url = db_models.Url(**url.dict(), uses=0, owner_id=owner.id) session.add(db_url) await session.commit() return api_models.Url(**url.dict(), id=db_url.id, owner_id=owner.id)
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 create_script( script_in: ScriptIn, session: AsyncSession = Depends(get_db_session) # noqa: B008 ): """Add a new script""" async with session.begin(): try: dbobj = await modeldb.create_script(session, script_in) except modeldb.ConstraintFailureError as exc: raise HTTPException(status_code=409, detail=str(exc)) from None session.add(dbobj) return dbobj
async def commit_db( db: AsyncSession, *, obj_callable: Callable, args: Optional[Union[List[Any], Tuple[Any, ...]]] = None, kwargs: Optional[Dict[str, Any]] = None ) -> _M: args, kwargs = args or [], kwargs or {} obj = await obj_callable(*args, **kwargs) db.add(obj) await db.commit() await db.refresh(obj) return obj
async def create(category: CategoryIn, db: AsyncSession = Depends(get_db)): try: # Extract the fields c = Category(**category.dict()) # Add it to the database db.add(c) await db.commit() return c except IntegrityError: raise HTTPException(status_code=409, detail="field 'name' must be unique")
async def get_db(): session = AsyncSession(engine) try: async with session.begin_nested(): yield session except PendingRollbackError: pass finally: try: await session.commit() except PendingRollbackError: pass await session.close()
async def save(self, db_session: AsyncSession): """ :param db_session: :return: """ try: db_session.add(self) return await db_session.commit() except SQLAlchemyError as ex: raise HTTPException( status_code=status.HTTP_422_UNPROCESSABLE_ENTITY, detail=repr(ex))