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} стал активен')
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
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
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} добавлен сервер')
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}')
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
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
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
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
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
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
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}')
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
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
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
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
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
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
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
def create(self, model: t.Type[BaseModel]) -> t.Type[BaseModel]: session.add(model) session.commit() return model
def __exit__(self, exc_type, exc_val, exc_tb): try: session.commit() except Exception: session.rollback() raise CustomException(error='transaction error', code=500)
def __exit__(self, exc_type, exc_val, exc_tb): try: session.commit() except Exception as e: session.rollback() raise e