Пример #1
0
    def _pay_imitation(self, server_id: int) -> None:
        time.sleep(random.randint(5, 15))
        obj = session.query(Server).get(server_id)
        obj.status = ServerStatus.ACTIVE
        session.commit()

        current_app.logger.info(f'Сервер с идентификатором {self.obj.id} стал активен')
Пример #2
0
    def update(self, obj, data: t.Mapping[str, t.Any]) -> t.Type[BaseModel]:
        for k, v in data.items():
            setattr(obj, k, v)

        session.commit()

        return obj
Пример #3
0
    def execute(
        self,
        nickname: str,
        email: str,
        password1: str,
        password2: str,
    ) -> Union[User, NoReturn]:
        if password1 != password2:
            raise CustomException('password1, 2 does not match', code=400)

        if self._is_exist(nickname=nickname, email=email):
            raise CustomException('already exists', 400)

        password = bcrypt.hashpw(
            password=password1.encode('utf-8'),
            salt=bcrypt.gensalt(),
        )

        user = User(nickname=nickname, email=email, password=password)

        try:
            session.add(user)
            session.commit()
        except IntegrityError as e:
            session.rollback()
            raise CustomException(str(e), code=500)

        return user
Пример #4
0
    def add_server(self, server: Server) -> None:
        if not self.has_free_slots():
            raise ValidationError('The rack has not free slots')

        session.add(server)
        session.commit()

        current_app.logger.info(f'В стойку с идентификатором {self.obj.id} добавлен сервер')
Пример #5
0
    def change_status(self, status: str) -> None:
        if self.is_deleted:
            raise ValidationError('Server is deleted.')

        self.obj.status = status
        session.commit()

        current_app.logger.info(f'Сервер с идентификатором {self.obj.id} изменил статус на {status}')
Пример #6
0
    async def run_requires_new(self, function, args, kwargs):
        if not session().is_active:
            session.begin()

        result = await function(*args, **kwargs)
        session.commit()

        return result
Пример #7
0
 async def decorator(*args, **kwargs):
     try:
         session.begin(subtransactions=True)
         result = await function(*args, **kwargs)
         session.commit()
     except Exception as e:
         session.rollback()
         raise e
     return result
Пример #8
0
    def execute(self, user_id: int, caption: str) -> Union[Post, NoReturn]:
        post = Post(user_id=user_id, caption=caption)

        try:
            session.add(post)
            session.commit()
        except IntegrityError as e:
            session.rollback()
            raise CustomException(str(e), code=500)

        return post
Пример #9
0
    async def run_required(self, function, args, kwargs):
        is_transaction_active = session().is_active

        if not is_transaction_active:
            session.begin(subtransactions=True)

        result = await function(*args, **kwargs)
        if not is_transaction_active:
            session.commit()

        return result
Пример #10
0
    def execute(self, user_id: int, post_id: int) -> Union[bool, NoReturn]:
        post = session.query(Post).filter(Post.id == post_id).first()

        if post.user_id != user_id:
            raise CustomException('do not have permission', code=401)

        try:
            session.delete(post)
            session.commit()
        except IntegrityError as e:
            raise CustomException(str(e), code=500)

        return True
Пример #11
0
    async def create_user(self, email: str, password1: str, password2: str,
                          nickname: str) -> Union[User, NoReturn]:
        if password1 != password2:
            raise PasswordDoesNotMatchException

        if (session.query(User).filter(
                or_(User.email == email, User.nickname == nickname)).first()):
            raise DuplicateEmailOrNicknameException

        user = User(email=email, password=password1, nickname=nickname)
        session.add(user)
        session.commit()

        return user
Пример #12
0
    def pay(self) -> None:
        if self.is_deleted:
            raise ValidationError('Server is deleted.')

        # имитация оплаты
        threading.Thread(
            target=self._pay_imitation,
            kwargs={'server_id': self.obj.id},
        ).start()

        self.mark_as_paid()
        self.obj.paid_at = datetime.datetime.now()
        session.commit()

        current_app.logger.debug(f'Оплачен сервер с идентификатором {self.obj.id}')
Пример #13
0
 def create(self, **args):
     args['created'] = datetime.datetime.utcnow()
     error_message = None
     try:
         new_model = self.model(**args)
         session.add(new_model)
         session.commit()
         self.model = new_model
     except IntegrityError as e:
         print(str(e))
         error_message = 'Faulty or a duplicate record'
     except Exception as e:
         print(str(e))
         error_message = str(e)
     finally:
         if error_message:
             session.rollback()
             raise Exception(error_message)
     return self.model
Пример #14
0
 def update(self, **args):
     error_message = None
     try:
         model = self.model
         for key, value in args.items():
             setattr(property, key, value)
         session.merge(model)
         session.commit()
         self.model = model
     except IntegrityError as e:
         print(str(e))
         error_message = 'Faulty or a duplicate record'
     except Exception as e:
         print(str(e))
         error_message = str(e)
     finally:
         if error_message:
             session.rollback()
             raise Exception(error_message)
     return self.model
Пример #15
0
    async def execute(
        self,
        email: str,
        password1: str,
        password2: str,
        nickname: str,
    ) -> Union[User, NoReturn]:
        if password1 != password2:
            raise CustomException(error='password does not match', code=400)

        if session.query(User).filter(User.email == email).first():
            raise CustomException(error='duplicated email', code=400)

        if session.query(User).filter(User.nickname == nickname).first():
            raise CustomException(error='duplicated nickname', code=400)

        user = User(email=email, password=password1, nickname=nickname)
        session.add(user)
        session.commit()

        return user
Пример #16
0
 def create(self, **args):
     args['created'] = datetime.datetime.utcnow()
     error_message = None
     try:
         # Creating user object
         property = PropertyModel(**args)
         # Saving to DB
         session.add(property)
         session.commit()
         self.property = property
     except IntegrityError as e:
         print(str(e))
         error_message = 'Faulty or a duplicate record'
     except Exception as e:
         print(str(e))
         error_message = str(e)
     finally:
         if error_message:
             session.rollback()
             raise Exception(error_message)
     return self.property
Пример #17
0
 def update(self, **args):
     if hasattr(self, 'property') is False:
         raise Exception("Property was not loaded")
     error_message = None
     try:
         property = self.property
         for key, value in args.items():
             setattr(property, key, value)
         # Saving to DB
         session.merge(property)
         session.commit()
         self.property = property
     except IntegrityError as e:
         print(str(e))
         error_message = 'Faulty or a duplicate record'
     except Exception as e:
         print(str(e))
         error_message = str(e)
     finally:
         if error_message:
             session.rollback()
             raise Exception(error_message)
     return self.property
Пример #18
0
 def create(self, **args):
     if 'type' not in args:
         args['type'] = 'default'
     args['created'] = datetime.datetime.utcnow()
     args['confirmation_token'] = random_alnum_string(32)
     error_message = None
     try:
         # Creating user object
         user = UserModel(**args)
         # Saving to DB
         session.add(user)
         session.commit()
         self.user = user
     except IntegrityError as e:
         print(str(e))
         error_message = 'Faulty or a duplicate record'
     except Exception as e:
         print(str(e))
         error_message = str(e)
     finally:
         if error_message:
             session.rollback()
             raise Exception(error_message)
     return self.user
Пример #19
0
    def execute(
        self,
        user_id: int,
        post_id: int,
        caption: str,
    ) -> Union[Post, NoReturn]:
        post = session.query(Post).filter(
            Post.id == post_id,
            Post.user_id == user_id,
        ).first()

        if not post:
            raise CustomException('post not found', code=404)

        post.caption = caption

        try:
            session.add(post)
            session.commit()
        except IntegrityError as e:
            session.rollback()
            raise CustomException(str(e), code=500)

        return post
Пример #20
0
 def create(self, model: t.Type[BaseModel]) -> t.Type[BaseModel]:
     session.add(model)
     session.commit()
     return model
Пример #21
0
 def __exit__(self, exc_type, exc_val, exc_tb):
     try:
         session.commit()
     except Exception:
         session.rollback()
         raise CustomException(error='transaction error', code=500)
Пример #22
0
 def __exit__(self, exc_type, exc_val, exc_tb):
     try:
         session.commit()
     except Exception as e:
         session.rollback()
         raise e