def get_chat_notifications(self, chat_id: int) -> int: """Возвращает количество не прочитанных пользователем сообщений в чате""" if not self.chats: raise NotFoundError("User is not a member of any chat") chat_id = str(chat_id) for id_, notifications in map(lambda chat: chat.split(':'), self.chats.split(';')): if id_ == chat_id: return int(notifications) raise NotFoundError("User is not a member of this chat")
def insert_order_history(self, db_connection, order_history_info): """ 새 주문이 생성된 시점 / 기존 주문이 변경되는 시점에 주문 상태 기록을 생성합니다. Args: order_status_id : 변경할 주문 상태 order_id : 주문 아이디 updated_at: 주문 생성 시점 account_id : 주문한 계정 Returns: cursor.lastrowid : 변경된 주문기록에 대한 아이디 Authors: [email protected](최지선) History: 2020.11.03(최지선) : 초기 생성 """ with db_connection.cursor() as cursor: insert_order_history_query = """ INSERT INTO order_status_history ( order_status_id, order_id, updated_at, account_id ) VALUES ( %(order_status_id)s, %(order_id)s, now(), %(account_id)s ) """ #order_id 가 여러 개 if type(order_history_info['order_id']) == tuple: row_list = [] for order in order_history_info['order_id']: new_dict = { "order_status_id": order_history_info['order_status_id'], 'order_id': order, 'account_id': order_history_info['account_id'] } cursor.execute(insert_order_history_query, new_dict) row_list.append(cursor.lastrowid) if len(row_list) != len(order_history_info['order_id']): raise NotFoundError('S000') return row_list # order_id 1 개 else: cursor.execute(insert_order_history_query, order_history_info) if not cursor.lastrowid: raise NotFoundError('S000') return cursor.lastrowid
async def post(self, candidate_id, *args, **kwargs): try: if not self.current_user.can_vote: raise DisableVoting async with objects.database.atomic_async(): candidate = await objects.get(Candidate, id=candidate_id) if self.current_user.id == candidate.user_id: raise DisableVoting("不能给自己投票") key = f'vote_user_{self.current_user.id}_date_{date.today()}' is_vote = redis.get(key) if is_vote: raise IsVoteError await objects.create(VoteEvent, vote_id=candidate.vote_id, voter_id=self.current_user.id, voter_avatar=self.current_user.avatar, voter_nickname=self.current_user.nickname, candidate_id=candidate.id, reach=1) candidate.number_of_votes += 1 await objects.update(candidate) now = datetime.now() time_max = datetime.combine(now, time.max) expire = int((time_max - now).total_seconds()) redis.set(key, '1', expire) self.finish( json.dumps({'number_of_votes': candidate.number_of_votes})) except Candidate.DoesNotExist: raise NotFoundError("参赛选手未找到")
async def get(self, pk, *args, **kwargs): try: await objects.get(Vote, id=pk) query = Vote.get_vote_info_by_pk(pk) vote = await objects.prefetch(query, VoteBanner.select()) vote = vote[0] vote.views += 1 await objects.update(vote) banners = [banner.image for banner in vote.banners] ret = dict( banners=banners, start_time=vote.start_time, end_time=vote.end_time, views=vote.views, announcement=vote.announcement, title=vote.title, description=vote.description, number_of_votes=int(vote.number_of_votes), number_of_candidates=vote.number_of_candidates, ) self.finish(json.dumps(ret, default=json_serializer)) except Vote.DoesNotExist: raise NotFoundError("投票活动不存在")
def find_by_id(self, entity_id): entity = self._find_by(id=entity_id).first() if not entity: message = "{} with id {} not found".format(self.type.__name__, entity_id) raise NotFoundError(message) return entity
async def get(self, pk, *args, **kwargs): try: await objects.get(Vote, id=pk) vote = await objects.prefetch(Vote.select().where(Vote.id == pk), VoteBanner.select()) vote = vote[0] banners = [{ 'id': banner.id, 'url': banner.image } for banner in vote.banners] ret = dict( banners=banners, start_time=vote.start_time, end_time=vote.end_time, announcement=vote.announcement, title=vote.title, description=vote.description, rules=vote.rules, ) self.finish(json.dumps(ret, default=json_serializer)) except Vote.DoesNotExist: raise NotFoundError("投票活动不存在")
def notFound(self, message): http_header = b"HTTP/1.1 404 Not Found\nContent-Type: text/html\n\n" self.request.sendall(http_header) fd = os.open(os.path.dirname(__file__) + "/html/404.html", os.O_RDONLY) self.read_and_send(fd, round(170 / self.size + 0.5)) raise NotFoundError(message)
def update_product_stock_quantity(self, db_connection, order_info): """ Args: product_id : 상품 아이디 color_id : 컬러 아이디 size_id : 사이즈 아이디 quantity : 주문 수량 discount_status_id : 할인여부 Returns: rows : 업데이트 된 열 수 Authors: [email protected](최지선) History: 2020.11.03(최지선) : 초기 생성 """ with db_connection.cursor() as cursor: update_product_stock_query = """ UPDATE product_options RIGHT JOIN products ON product_options.product_id=products.id SET stock_quantity=stock_quantity-%(quantity)s WHERE is_delete=0 AND sales_status_id=2 AND display_status_id=2 AND discount_status_id=%(discount_status_id)s AND products.id=%(product_id)s AND size_id=%(size_id)s AND color_id=%(color_id)s """ cursor.execute(update_product_stock_query, order_info) rows = cursor.rowcount if not rows: raise NotFoundError('S000') return rows
async def get(self, pk, *args, **kwargs): try: vote = await objects.get(Vote, id=pk) self.finish({'detail': vote.rules}) except Vote.DoesNotExist: raise NotFoundError("投票未找到")
async def get(self, user_id, *args, **kwargs): try: user = await objects.get(User, id=user_id) votes_query = Candidate.get_admin_vote_info(user.id) candidates = await objects.prefetch(votes_query, CandidateImage.select()) votes = [{ 'title': candidate.vote.title, 'description': candidate.vote.description, 'vote_id': candidate.vote.id, 'cover': candidate.cover, 'declaration': candidate.declaration, 'registration_time': candidate.create_time, 'vote_start_time': candidate.vote.start_time, 'vote_end_time': candidate.vote.end_time, 'total_vote': candidate.total_vote, 'total_profit': candidate.total_profit, 'images': [image.url for image in candidate.images], 'id': candidate.id } for candidate in candidates] ret = dict(avatar=user.avatar, nickname=user.nickname, name=user.name, mobile=user.mobile[:3] + '****' + user.mobile[-4:] if user.mobile else '', votes=votes) self.finish(json.dumps(ret, default=json_serializer)) except User.DoesNotExist: raise NotFoundError("用户不存在")
async def post(self, candidate_id, *args, **kwargs): param = self.request.body.decode("utf-8") data = json.loads(param) gift_send_form = GiftSendForm.from_json(data) if gift_send_form.validate(): user = self.current_user gift_id = gift_send_form.gift_id.data num = gift_send_form.num.data async with objects.database.atomic_async(): try: gift = await objects.get(Gift, id=candidate_id) candidate = await objects.get(Candidate, id=candidate_id) out_trade_no = async_weixin_pay.out_trade_no ret = await async_weixin_pay.jsapi( openid=user.openid, body=gift.name, out_trade_no=out_trade_no, total_fee=int(gift.price * num * 100), ) redis.hmset( out_trade_no, { 'gift_id': f'{gift_id}', 'candidate_id': f'{candidate_id}', 'amount': f'{gift.price * num}', 'number_of_gifts': f'{num}', 'voter_id': f'{user.id}', 'voter_nickname': f'{user.nickname}', 'voter_avatar': f'{user.avatar}', 'image': f'{gift.image}', 'reach': f'{gift.reach*num}', 'gift_name': f'{gift.name}', 'vote_id': f'{candidate.vote_id}' }, ) redis.expire(out_trade_no, 10 * 60) print(out_trade_no) self.finish(ret) except Gift.DoesNotExist: raise NotFoundError("礼物不存在") except Candidate.DoesNotExist: raise NotFoundError("选手不存在")
def find_first_by(self, **kwargs): entity = self._find_by(**kwargs).first() if not entity: args_list = map(lambda value: str(value), kwargs.values()) arguments = ', '.join(args_list) raise NotFoundError("{} with id {} not found".format( self.type.__name__, arguments)) return entity
def find_or_fail(id): meeting = Meeting.find(id) if not meeting: raise NotFoundError("Meeting id not found") return meeting
def delete_student(id): try: student = Student.query.get(id) db.session.delete(student) db.session.commit() return student_schema.jsonify(student) except sqlalchemy.orm.exc.UnmappedInstanceError: raise NotFoundError('UnmappedInstanceError occured', 404)
async def delete(self, gift_id, *args, **kwargs): try: gift = await objects.get(Gift, id=gift_id) gift.is_void = True await objects.update(gift) self.set_status(204) self.finish() except Gift.DoesNotExist: raise NotFoundError("礼物不存在")
async def get(self, candidate_id, *args, **kwargs): try: await objects.get(Candidate, id=candidate_id) await super().get(candidate_id, *args, **kwargs) except Candidate.DoesNotExist: raise NotFoundError("参赛选手未找到")
def get_item(item_id, model, user=None): item = db.session.query(model).get(item_id) if item is None: raise NotFoundError(model) if user and item.user != user: return {'success': False, 'errors': ['Forbidden.']} else: return {'success': True, 'payload': item.serialize}
def get_entry(entry_id): try: entry = Entry.query.filter_by(id=entry_id).one() return [entry, None] except NoResultFound: err_obj = NotFoundError('entry', entry_id).get() return [None, err_obj] except Exception: err_obj = gratitude_error.get()['error'] return [None, err_obj]
async def post(self, vote_id, *args, **kwargs): param = self.request.body.decode("utf-8") data = json.loads(param) candidate_form = CandidateForm.from_json(data) if candidate_form.validate(): user = self.current_user is_new = True if not user.mobile else False declaration = candidate_form.declaration.data images = candidate_form.images.data async with objects.database.atomic_async(): try: await objects.get(Vote, id=vote_id) if is_new: mobile = candidate_form.mobile.data code = candidate_form.code.data redis_key = "{}_{}".format(mobile, code) if not redis.get(redis_key): raise ErrorCode user.mobile = mobile user.name = candidate_form.name.data await objects.update(user) candidate = await objects.get(Candidate, user=user, vote_id=vote_id) if not candidate.is_active: raise DisableVoting("您已被禁止参加此次投票!") raise DuplicateError except Candidate.DoesNotExist: count = await objects.count( Candidate.select().where(Candidate.vote_id == vote_id)) number = "%03d" % (count + 1) candidate = await objects.create(Candidate, vote_id=vote_id, declaration=declaration, cover=images[0], number=number, user=user) for image in images: await objects.create(CandidateImage, candidate=candidate, url=image) self.finish({"candidate_id": candidate.id}) except Vote.DoesNotExist: raise NotFoundError("投票不存在")
def find_or_fail(id): """ Find a room by id """ room = Room.find(id) if not room: raise NotFoundError("Room id not found") return room
async def put(self, pk, *args, **kwargs): try: async with objects.database.atomic_async(): vote = await objects.get(Vote, id=pk) param = self.request.body.decode("utf-8") data = json.loads(param) form = VoteUpdateForm.from_json(data) if form.validate(): data = dict(form.data) banners = data.pop('banners', []) new_banners = [] old_banners = [] for b in banners: if b['id'] is None: new_banners.append(b) else: old_banners.append(b) ids = [b['id'] for b in old_banners] data['cover'] = banners[0]['url'] for key, value in data.items(): setattr(vote, key, value) _banners = await objects.execute(VoteBanner.select().where( VoteBanner.vote == vote, VoteBanner.id.not_in(ids))) for banner in _banners: await objects.delete(banner) if new_banners: for i, b in enumerate(new_banners): banner = await objects.create(VoteBanner, vote_id=vote.id, image=b['url']) new_banners[i]['id'] = banner.id banners = old_banners + new_banners await objects.update(vote) ret = model_to_dict(vote, exclude=[ Vote.views, Vote.cover, Vote.create_time, Vote.update_time ]) ret['banners'] = banners self.finish(json.dumps(ret, default=json_serializer)) else: ret = {} self.set_status(400) for field in form.errors: ret[field] = form.errors[field][0] self.finish(ret) except Vote.DoesNotExist: raise NotFoundError("投票活动不存在")
def edit_seller_detail_infos(self, seller_info, seller_profile, seller_back, db_connection): """ 셀러의 상세 정보를 수정합니다. Authors: [email protected](임은수) History: 2020.11.07(임은수) : 초기 생성 """ s3 = boto3.client("s3", aws_access_key_id=config.S3_ACCESS_KEY_LES, aws_secret_access_key=config.S3_SECRET_KEY_LES) # 셀러 프로필 이미지가 있으면 if seller_profile: s3.upload_fileobj( seller_profile, config.S3_BUCKET_LES, "seller_profile/{}".format(seller_info['account_id']), ExtraArgs={"ContentType": seller_profile.content_type}) seller_info[ "profile_image"] = "https://eunsulim.s3.ap-northeast-2.amazonaws.com/seller_profile/{}".format( seller_info['account_id']) result = self.seller_dao.edit_seller_profile( seller_info, db_connection) # 셀러 배경 이미지가 있으면 if seller_back: s3.upload_fileobj( seller_back, config.S3_BUCKET_LES, "seller_back/{}".format(seller_info['account_id']), ExtraArgs={"ContentType": seller_back.content_type}) seller_info[ "background_image_url"] = "https://eunsulim.s3.ap-northeast-2.amazonaws.com/seller_back/{}".format( seller_info['account_id']) result = self.seller_dao.edit_seller_back(seller_info, db_connection) # 수정할 데이터를 가져와서 넣어준다. seller_data = self.seller_dao.get_seller_detail_infos( seller_info, db_connection) if seller_data: # 가져온 데이터를 수정한다. result = self.seller_dao.edit_seller_detail_infos( seller_info, db_connection) return 'S100' #seller_data 가 None 인 경우 raise NotFoundError('S108')
def modify_student(id): if (not request.json.get('first_name')) or ( not request.json.get('last_name')): raise BadRequest('first_name and last_name required.', 400) try: student = Student.query.get(id) fname = request.json['first_name'] lname = request.json['last_name'] student.first_name = fname student.last_name = lname db.session.commit() except sqlalchemy.orm.exc.UnmappedInstanceError: raise NotFoundError('UnmappedInstanceError occured', 404)
def validate_response(response): """validate_response """ error_suffix = " response={!r}".format(response) if response.status_code in (status.HTTP_401_UNAUTHORIZED, status.HTTP_403_FORBIDDEN): raise AuthError("operation=auth_error," + error_suffix, response) if response.status_code == status.HTTP_404_NOT_FOUND: raise NotFoundError("operation=not_found_error," + error_suffix, response) if status.is_client_error(code=response.status_code): raise ClientError("operation=client_error," + error_suffix, response) if status.is_server_error(code=response.status_code): raise ServerError("operation=server_error," + error_suffix, response)
async def get(self, vote_id, candidate_id, *args, **kwargs): try: await objects.get(Vote, id=vote_id) query = Candidate.query_candidates_by_vote_id( vote_id=vote_id).where(Candidate.id == candidate_id) candidates = await objects.prefetch(query, CandidateImage.select()) if not len(candidates): raise NotFoundError("选手不存在") candidate = candidates[0] ret = dict(name=candidate.user.name, number=candidate.number, images=[image.url for image in candidate.images], declaration=candidate.declaration, number_of_votes=candidate.number_of_votes, diff=candidate.candidate.diff, rank=candidate.candidate.vote_rank) self.finish(json.dumps(ret)) except Vote.DoesNotExist: raise NotFoundError("投票不存在")
def from_file(cls, promotion_json, user, create_products=False): product_ids = set( map(lambda prom: prom.get('product_id'), promotion_json)) products = { p.id: p for p in Product.query.filter(Product.id.in_(product_ids)) } ret = [] for promotion in promotion_json: product = products.get(promotion['product_id']) if not product: product_id = promotion['product_id'] if not create_products: raise NotFoundError( 'Product {} not found'.format(product_id), payload={'id': product_id}) product = Product(id=product_id, user_id=user.id, name=promotion['product_name'], description=promotion['product_description'], price=promotion['price']) db.session.add(product) products[product.id] = product if product.user_id != user.id: raise ForbiddenError( 'Forbidden', payload={ 'error': 'User cannot create discounts for these products.' }) for attr, pattr in [('product_name', 'name'), ('product_description', 'description'), ('price', 'price')]: promotion.setdefault(attr, getattr(product, pattr)) promotion_obj = cls(**promotion) ret.append(promotion_obj) if ret: db.session.add_all(ret) db.session.commit() return ret
async def put(self, user_id, *args, **kwargs): try: user = await objects.get(User, id=user_id) param = self.request.body.decode("utf-8") data = json.loads(param) form = UserStatusForm.from_json(data) if form.validate(): user.can_vote = form.can_vote.data await objects.update(user) self.finish({'user_id': user_id, 'can_vote': user.can_vote}) else: self.set_status(400) self.finish({'can_vote': form.errors['can_vote']}) except User.DoesNotExist: raise NotFoundError("用户不存在")
async def get(self, candidate_id, *args, **kwargs): try: await objects.get(Candidate, id=candidate_id) query = VoteEvent.get_vote_rank(candidate_id) ranks = await objects.execute(query) ret = [] for rank in ranks: ret.append( dict(voter_avatar=rank.voter_avatar, voter_nickname=rank.voter_nickname, number_of_votes=int(rank.number_of_votes), vote_rank=rank.vote_rank)) self.finish(json.dumps(ret)) except Candidate.DoesNotExist: raise NotFoundError("参赛选手未找到")
def get_for_employee(self, employee_id, year=None, month=None): if employee_id is None: raise NotFoundError() if year and month: time_sheet = _get_or_create( use_case=self, year=year, month=month, employee_id=employee_id) return [self.time_sheet_provider.serialize(time_sheet)] elif year: time_sheets = self.storage.find_by(employee_id=employee_id, year=year) elif month: time_sheets = self.storage.find_by(employee_id=employee_id, month=month) else: time_sheets = self.storage.find_by(employee_id=employee_id) return self._serialize_many(time_sheets)
def seller_detail_infos(self, seller_info, db_connection): """ 셀러의 상세 정보를 가져옵니다. Authors: [email protected](임은수) History: 2020.11.07(임은수) : 초기 생성 """ seller_data = self.seller_dao.get_seller_detail_infos( seller_info, db_connection) if seller_data: return {'seller_data': seller_data} #seller_data 가 None 인 경우 raise NotFoundError('S108')