Exemplo n.º 1
0
    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(), [])
Exemplo n.º 2
0
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"}
Exemplo n.º 3
0
async def update_task(db: AsyncSession, task_create: task_schema.TaskCreate,
                      original: task_model.Task) -> task_model.Task:
    original.title = task_create.title
    db.add(original)
    await db.commit()
    await db.refresh(original)
    return original
Exemplo n.º 4
0
async def create_task(db: AsyncSession,
                      task_create: task_schema.TaskCreate) -> task_model.Task:
    task = task_model.Task(**task_create.dict())
    db.add(task)
    await db.commit()
    await db.refresh(task)
    return task
Exemplo n.º 5
0
async def test_citext_integration(sess: AsyncSession) -> None:
    await sess.execute(text("create extension if not exists citext"))

    Base = declarative_base(metadata=MetaData())

    class MyTable(Base):
        __tablename__ = "citext_table"

        id = Column(Integer(), primary_key=True)
        email = Column(CITEXT)  # type: ignore

        def __repr__(self) -> str:
            return f'MyTable(id={self.id}, email="{self.email}")'

    conn = await sess.connection()
    await conn.run_sync(Base.metadata.create_all)

    row = MyTable(id=1, email="*****@*****.**")  # type: ignore

    sess.add(row)  # type: ignore
    await sess.commit()

    # Expunge the row from the session so we don't fetch it from the cache
    # If you don't do this, the retrieved row will come from the local session
    # and will not have any preprocessor rules applied
    sess.expunge(row)  # type: ignore

    from_db = await (sess.execute(
        select(MyTable).where(MyTable.email == "*****@*****.**")))
    (res, ) = from_db.one()
    assert res.id == 1
Exemplo n.º 6
0
async def create_user(db: AsyncSession, user: schema.UserCreate):
    hashed_password = await get_password_hash(user.password)
    db_user = model.User(email=user.email, hashed_password=hashed_password)
    db.add(db_user)
    await db.commit()
    await db.refresh(db_user)
    return db_user
Exemplo n.º 7
0
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
Exemplo n.º 8
0
async def create_election(db: AsyncSession, election: schema.ElectionBase,
                          user_id: int):
    db_election = model.Election(**election.dict(), owner_id=user_id)
    db.add(db_election)
    await db.commit()
    await db.refresh(db_election)
    return db_election
Exemplo n.º 9
0
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)
Exemplo n.º 10
0
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
Exemplo n.º 11
0
 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
Exemplo n.º 12
0
 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
Exemplo n.º 13
0
    async def add(self, bot, event: Message, sess: AsyncSession, url: str):
        async with aiohttp.ClientSession() as session:
            try:
                async with session.get(url) as res:
                    data: bytes = await res.read()
            except aiohttp.client_exceptions.InvalidURL:
                await bot.say(event.channel, f"`{url}`은 올바른 URL이 아니에요!")
                return
            except aiohttp.client_exceptions.ClientConnectorError:
                await bot.say(event.channel, f"`{url}`에 접속할 수 없어요!")
                return

        if not data:
            await bot.say(event.channel, f"`{url}`은 빈 웹페이지에요!")
            return

        f = feedparser.parse(data)

        if f.bozo != 0:
            await bot.say(event.channel, f"`{url}`은 올바른 RSS 문서가 아니에요!")
            return

        feed = RSSFeedURL()
        feed.channel = event.channel
        feed.url = url
        feed.updated_at = max([
            dateutil.parser.parse(entry.published).astimezone(UTC)
            for entry in f.entries
        ])

        sess.add(feed)
        await sess.commit()

        await bot.say(event.channel,
                      f"<#{event.channel}> 채널에서 `{url}`을 구독하기 시작했어요!")
Exemplo n.º 14
0
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)
Exemplo n.º 15
0
 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
Exemplo n.º 16
0
 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
Exemplo n.º 17
0
 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]))
Exemplo n.º 18
0
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
Exemplo n.º 19
0
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()
Exemplo n.º 20
0
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
Exemplo n.º 21
0
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()
Exemplo n.º 22
0
 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
Exemplo n.º 23
0
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!"}
Exemplo n.º 24
0
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()
Exemplo n.º 25
0
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")
Exemplo n.º 26
0
Arquivo: urls.py Projeto: TrixiS/cultr
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)
Exemplo n.º 27
0
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
Exemplo n.º 28
0
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
Exemplo n.º 29
0
    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))
Exemplo n.º 30
0
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")