async def archive(request, year): posts = await Post.filter( Q(status=Post.STATUS_ONLINE), Q(created_at__gte=f'{ year }-01-01'), Q(created_at__lt=f'{ int(year) + 1 }-01-01')).order_by('-id') archives = [(year, posts)] return {'archives': archives}
def test_q_complex_int3(self): q = Q(Q(id__lt=5, id__gt=50, join_type="OR"), join_type="AND", intnum=80) r = q.resolve(IntFields, {}, {}, IntFields._meta.basequery) self.assertEqual(r.where_criterion.get_sql(), '"intnum"=80 AND ("id"<5 OR "id">50)')
async def get_player( parameters: route_models.Player ): player_name = parameters.player_name participant = await Participant.filter( Q(player__alternative_names__icontains=player_name)|Q(player_name=player_name) ).prefetch_related('player').order_by('-id').first() if participant is None: all_players = await Player.all() for player in all_players: if player_name in player.alternative_names: participant = await Participant.filter(player__id=player.id).prefetch_related('player').order_by('-id').first() break if participant: latest_participant = await participant return { 'platform': get_platform(latest_participant.player.platform_url), 'api_id': latest_participant.player.api_id, 'in_database': True } else: return { 'in_database': False }
async def emojistats(self, ctx, member: discord.Member = None): """Shows you statistics about the emoji usage on author.""" embeds = [] guild = ctx.guild if member == None: member = ctx.author data = (await models.EmojiUsageStat.filter( Q(guild_id=guild.id) & Q(user_id=member.id)).order_by("-amount").values( "emoji_id", "amount", "last_usage")) total = sum([d["amount"] for d in data]) for data in functions.list_to_matrix(data): embed = discord.Embed(color=self.bot.color) embed.set_author(name=member, icon_url=member.avatar.url) embed.description = "{}\n\n{}".format( self.get_emoji_stats(ctx, data), "Toplam: `{}`".format(total), ) embeds.append(embed) menu = menus.MenuPages( timeout=30, clear_reactions_after=True, source=paginator.EmbedSource(data=embeds), ) try: await menu.start(ctx) except IndexError: await ctx.send("Kayıt bulunamadı!")
async def validate_login(username, password): user = await User.filter(Q(username=username) | Q(email=username)).first() if not user: return False, None if check_password_hash(user.password, password): return True, user return False, None
async def get_entries(user_id: int, params, keywords: List[str], date_min: datetime, date_max: datetime, jrnl_id: Optional[int], deleted: bool = False) -> List[Entry]: if deleted: query = Entry.filter(journal__user_id=user_id) else: query = Entry.filter(journal__user_id=user_id, deleted_on=None) if jrnl_id: query = query.filter(journal_id=jrnl_id) if date_min: query = query.filter(Q(date__gt=date_min)) if date_max: query = query.filter(Q(date__lt=date_max)) if params.method.lower() == "or": query = query.prefetch_related("keywords") query = query.filter(Q(keywords__word__in=keywords)) entries_to_return = await query.all().offset(params.skip ).limit(params.limit) else: entries = await query.all().offset(params.skip).limit(params.limit) await Entry.fetch_for_list(entries, "keywords") entries_to_return = list() for entry in entries: words = [w.word.lower() for w in entry.keywords] if all(kw.lower() in words for kw in keywords): entries_to_return.append(entry) return entries_to_return
async def get_events(self, ctx, from_timestamp: int = None): """Format : !!MyEvents <from_timestamp?>""" reply_msg = '' user, _ = await User.get_or_create(id=ctx.author.id) if from_timestamp is not None: from_dt = datetime_from_timestamp(from_timestamp) events = await Event.filter( Q(author_message__user=user) & Q(scheduled_dt__gte=from_dt)).order_by('scheduled_dt') else: events = await Event.filter(author_message__user=user ).order_by('scheduled_dt') if events is not None and len(events) > 0: reply_msg += 'Your current events:\n' for event in events: if len(reply_msg) > MSG_MAX_LENGTH: reply_msg += 'More events left that could not be displayed here.\n' reply_msg += f'Reply with `!!MyEvents {timestamp_from_datetime(event.scheduled_dt)} to show remaining events' break reply_msg += f'|{event.id}|{render_time(event.scheduled_dt, user)}|' \ f'{render_time_diff(utc_now(), event.scheduled_dt)}|{event.name}|\n' reply_msg += 'Reply with `!!CancelEvent id` or `!!CancelEvent all` to delete events' else: reply_msg += 'You don\'t have any events.' await ctx.reply(reply_msg)
async def search(cls, attributes=None, **query): fs_map = cls._meta.fields_map search = query.get('search') page = int(query.pop('page')) if query.get('page') else 1 limit = int(query.pop('limit')) if query.get('limit') else 15 order_by = query.pop('order_by') if query.get('order_by') else 'id' if not attributes: attributes = [a for a in fs_map.keys() if isinstance(fs_map[a], fields.CharField)] for k, v in query.items(): if isinstance(fs_map.get(k.split('__')[0]), fields.DatetimeField): query[k] = ciso8601.parse_datetime(v) if search: query.pop('search') if isinstance(search, list): attr_dict_list = [{a + '__in': search} for a in attributes] else: attr_dict_list = [{a + '__icontains': search} for a in attributes] q_list = [Q(**a) for a in attr_dict_list] count = await cls.filter(Q(*q_list, join_type="OR")).filter(**query).count() results = await cls.filter(Q(*q_list, join_type="OR")).filter(**query) \ .limit(limit).offset((page - 1) * limit).order_by(order_by) else: count = await cls.filter(**query).count() results = await cls.filter(**query).limit(limit).offset((page - 1) * limit).order_by(order_by) return results, count
async def snooze(self, ctx, duration: Duration = DurationHolder(5, 'm')): """remind_snooze_help""" duration_seconds = duration.to_seconds(ctx) if duration_seconds <= 0: await MessageUtils.send_to(ctx, "NO", "reminder_time_travel") return if isinstance(ctx.channel, DMChannel): target_criteria = Q(dm=1, status=ReminderStatus.DeliveredFirst) | Q(dm=0, status=ReminderStatus.DeliveredAlternative) else: target_criteria = Q(channel_id=ctx.channel.id) & (Q(dm=0, status=ReminderStatus.DeliveredFirst) | Q(dm=1, status=ReminderStatus.DeliveredAlternative)) target_reminder = await Reminder.get_or_none(Q(user_id=ctx.author.id) & target_criteria).order_by('-time').limit(1) if target_reminder is None: await MessageUtils.send_to(ctx, "NO", "reminder_not_found") return new_reminder = target_reminder.clone() new_reminder._custom_generated_pk = False new_reminder.status = ReminderStatus.Pending new_reminder.send = datetime.now().timestamp() new_reminder.time = time.time() + duration_seconds await new_reminder.save() if duration_seconds <= 10: self.handling.add(new_reminder.id) self.bot.loop.create_task( self.run_after(duration_seconds, self.deliver(new_reminder))) mode = "dm" if new_reminder.dm else "here" await MessageUtils.send_to(ctx, "YES", f"reminder_confirmation_{mode}", duration=duration.length, duration_identifier=duration.unit)
async def my_tickets(self, ctx: SlashContext, name: str): lottery = await Lottery.get_or_none(name=name) if not lottery: return await ctx.send( f"{ctx.author.mention}, error, sweepstake `{name}` doesn't exist", delete_after=DELETE_AFTER, ) tickets = await Ticket.filter( Q(lottery__id=lottery.id) & Q(user__id=ctx.author.id)) widget = Embed( description=f"You have `{len(tickets)}` tickets for `{name}`", color=GREEN, title=f"{name} tickets", ) widget.set_thumbnail(url=PROJECT_THUMBNAIL) if len(tickets): widget.add_field( name="Ticket numbers:", value=f"`{', '.join([str(_.ticket_number) for _ in tickets])}`", inline=False, ) await ctx.send( content=ctx.author.mention, embed=widget, delete_after=DELETE_AFTER, )
def find_contact( cls, user1_id: int, user2_id: int) -> queryset.QuerySetSingle[Optional[Contact]]: return cls.filter( Q(Q(user1_id=user1_id, user2_id=user2_id), Q(user1_id=user2_id, user2_id=user1_id), join_type='OR')).get_or_none()
async def register(self): """ Hàm dùng cho việc đăng ký tài khoản người dùng :return: object ** Lưu ý: hàm cần phải trả về một object khớp với user_type_defs trong file Schema dùng cho GraphQL """ email_regex = "^[a-zA-Z0-9_.+-]+@[a-zA-Z0-9-]+\.[a-zA-Z0-9-.]+$" phone_regex = "^\+?(?:03|05|07|08|09)(?:\d){8}$" # Các đầu số 03, 05, 07, 08, 09 user = await User.filter( Q(username=self.username) | Q(email=self.email) | Q(phone=self.phone)) if user: return { 'error': 'Username, Email hoặc Số điện thoại đã tồn tại!', } elif re.search(email_regex, self.email) is None: return {'error': 'Email không đúng định dạng!'} elif re.search(phone_regex, self.phone) is None: return {'error': 'Số điện thoại không đúng định dạng!'} else: new_user = await User.create( status=self.status, username=self.username, password=LioPassword().hash_password(password=self.password), email=self.email, phone=self.phone, ) return {'user': new_user}
async def get_reminders(self, ctx, from_timestamp: int = None): """Format : !!MyReminders <from_timestamp?>""" reply_msg = '' user, _ = await User.get_or_create(id=ctx.author.id) if from_timestamp is not None: from_dt = datetime_from_timestamp(from_timestamp) reminders = await Reminder.filter(Q(for_message__user=user) & Q(expire_dt__gte=from_dt)).order_by('expire_dt') else: reminders = await Reminder.filter(for_message__user=user).order_by('expire_dt') if reminders is not None and len(reminders) > 0: reply_msg += 'Your current reminders:\n' for reminder in reminders: if len(reply_msg) > MSG_MAX_LENGTH: reply_msg += 'More reminders left that could not be displayed here.\n' reply_msg += f'Reply with `!!MyReminders {timestamp_from_datetime(reminder.id)} to show remaining reminders' break reply_msg += f'|{reminder.id}|{render_time(reminder.expire_dt, user)}|' \ f'{render_time_diff(utc_now(), reminder.expire_dt)}|{reminder.info}|\n' reply_msg += 'Reply with `!!ClearReminder id` or `!!ClearReminder all` to delete reminders' else: reply_msg += 'You don\'t have any reminders.' await ctx.reply(reply_msg)
async def comment_ids_liked_by(self, user_id): cids = [c.id for c in await self.comments] if not cids: return [] queryset = await ReactItem.filter(Q(user_id=user_id), Q(target_id__in=cids), Q(target_kind=K_COMMENT)) return [item.target_id for item in queryset]
async def test_filter_not_with_or(self): await Tournament.create(name="0") await Tournament.create(name="1") await Tournament.create(name="2") tournaments = await Tournament.filter(Q(name="1") | ~Q(name="2")) self.assertEqual(len(tournaments), 2) self.assertSetEqual({t.name for t in tournaments}, {"0", "1"})
async def test_filter_not_with_or(self): await Tournament.create(name='0') await Tournament.create(name='1') await Tournament.create(name='2') tournaments = await Tournament.filter(Q(name='1') | ~Q(name='2')) self.assertEqual(len(tournaments), 2) self.assertSetEqual({t.name for t in tournaments}, {'0', '1'})
async def ipnsFeedsNeedSync(minutes=10): now = datetime.now() maxdate = now - timedelta(minutes=minutes) filter = Q(active=True) & \ (Q(resolvenext__lt=maxdate) | Q(resolvenext__isnull=True)) return await IPNSFeed.filter(filter).order_by('-resolvedlast')
async def search_courses_by_title( title_query: str, ) -> List[SearchedCourseData]: """Поиск курсов по их названию.""" courses = await ( Course.filter(Q(is_private=False) & Q(title__icontains=title_query)).values( "id", "title", "description")) return courses
async def hashmarksByObjTags(taglist, **kw): tags = iptags.ipTagsFormatList(taglist, **kw) filter = Q(objtags__name__in=tags) for tag in tags: filter = filter | Q(objtags__name__icontains=tag) return await Hashmark.filter(filter)
async def tag(request, tag_id): tag = await Tag.cache(tag_id) if not tag: abort(404) post_ids = await PostTag.filter(tag_id=tag_id).values_list('post_id', flat=True) posts = await Post.filter(Q(status=Post.STATUS_ONLINE), Q(id__in=post_ids)).order_by('-id').all() return {'tag': tag, 'posts': posts}
def test_q_complex_char3(self): q = Q(~Q(char__lt=5, char__gt=50, join_type="OR"), join_type="AND", char_null=80) r = q.resolve(CharFields, {}, {}, CharFields._meta.basequery) self.assertEqual( r.where_criterion.get_sql(), "\"char_null\"='80' AND NOT (\"char\"<'5' OR \"char\">'50')", )
async def user_status(request, user): post_images = await Item.filter(Q(user=user) & Q(type='image')).count() post_texts = await Item.filter(Q(user=user) & Q(type='text')).count() return json( dict(id=user.id, nickname=user.nickname, email=user.email, post_images=post_images, post_texts=post_texts))
async def read_transcations(user_email: str): """ 이메일을 조회해서 이메일에 맞는 거래 내역을 분석합니다. """ user_customer = await Customers.get(email=user_email) user_account = await Accounts.get(customer_id=user_customer.pk) user_queryset: TranscationOut = await Transcation.filter( Q(customer_id=user_customer.pk) | Q(account_id=user_account.pk)) return user_queryset
async def search(cls, filters: dict, size=None, offset=None, id_only=False) -> SearchResults: """Search matches Arguments: filters {dict} -- Filters for match search Keyword Arguments: size {[int]} -- Nmber of results returned (default: {None}) offset {[int]} -- Offset of the first result for pagination (default: {None}) id_only {bool} -- Whether to return only a list of ids (default: {False}) Returns: SearchResults -- A list of matches and total count """ queries: List[Q] = [] rule_id = filters.get("rule_id") if rule_id is not None: queries.append(Q(rule_id=rule_id)) snapshot_id = filters.get("snapshot_id") if snapshot_id is not None: queries.append(Q(snapshot_id=snapshot_id)) from_at = filters.get("from_at") if from_at is not None: from_at = convert_to_datetime(from_at) queries.append(Q(created_at__gt=from_at)) to_at = filters.get("to_at") if to_at is not None: to_at = convert_to_datetime(to_at) queries.append(Q(created_at__lt=to_at)) query = Q(*queries) # Run search instance = cls(model=Match, query=query, prefetch_related=["snapshot", "rule", "script"]) results = await instance._search(size=size, offset=offset, id_only=id_only) if id_only: return SearchResults(results=cast(List[UUID], results.results), total=results.total) matches: List[MatchModel] = [ match.to_model() for match in cast(List[Match], results.results) ] return SearchResults(results=matches, total=results.total)
def _get_subs(self, uid=None, type_=None, type_id=None, live=None, dynamic=None, at=None, bot_id=None) -> QuerySet[Sub]: """获取指定的订阅数据""" kw = locals() del kw['self'] kw['type'] = kw.pop('type_') filters = [Q(**{key: value}) for key, value in kw.items() if value != None] return Sub.filter(Q(*filters, join_type='AND'))
async def hashmarkSourceSearch(name=None, type=0, url=None): filter = Q(type=type) if name: filter = filter & Q(name=name) if url: filter = filter & Q(url=url) return await HashmarkSource.filter(filter).first()
async def get_old_winning_pool() -> int: """Return winning pool for past lotteries without winners (aka with 'ended' status and has_winners="False")""" qs = ( await Lottery.filter(Q(status=LotteryStatus.ENDED) & Q(has_winners=False)) .prefetch_related("tickets") .annotate(total_tickets=Count("tickets")) ) # TODO: waiting for response to rewrite this into orm # https://github.com/tortoise/tortoise-orm/issues/683 return sum([_.total_tickets * _.ticket_price for _ in qs])
async def fetch_infraction_pages(guild_id, query, amount, fields, requested): key = get_key(guild_id, query, fields, amount) if query == "": infs = await Infraction.filter(guild_id=guild_id ).order_by("-id").limit(50) else: subfilters = [] if "[user]" in fields and isinstance(query, int): subfilters.append(Q(user_id=query)) if "[mod]" in fields and isinstance(query, int): subfilters.append(Q(mod_id=query)) if "[reason]" in fields: subfilters.append(Q(reason__icontains=str(query))) infs = await Infraction.filter( Q(Q(*subfilters, join_type="OR"), guild_id=guild_id, join_type="AND")).order_by("-id").limit(int(amount)) longest_type = 4 longest_id = len(str(infs[0].id)) if len(infs) > 0 else len( Translator.translate('id', guild_id)) longest_timestamp = max(len(Translator.translate('timestamp', guild_id)), 19) types = dict() for inf in infs: t = inf.type.lower() longest_type = max(longest_type, len(Translator.translate(t, guild_id))) if t not in types: types[t] = 1 else: types[t] += 1 header = ", ".join( Translator.translate(f"{k}s", guild_id, count=v) for k, v in types.items()) name = await Utils.username(query) if isinstance( query, int) else await Utils.clean(bot.get_guild(guild_id).name) title = f"{Emoji.get_chat_emoji('SEARCH')} {Translator.translate('inf_search_header', guild_id, name=name, page_num=100, pages=100)}\n```md\n\n```" page_header = get_header(longest_id, 37, longest_type, longest_timestamp, guild_id) mcount = 2000 - len(header) - len(page_header) - len(title) out = "\n".join( f"{Utils.pad(str(inf.id), longest_id)} | <@{Utils.pad(str(inf.user_id), 37)}> | <@{Utils.pad(str(inf.mod_id), 37)}> | {datetime.fromtimestamp(inf.start)} | {Utils.pad(Translator.translate(inf.type.lower(), guild_id), longest_type)} | {Utils.trim_message(inf.reason, 1000)}" for inf in infs) pages = Pages.paginate(out, max_chars=mcount) if bot.redis_pool is not None: GearbotLogging.debug(f"Pushing placeholders for {key}") pipe = bot.redis_pool.pipeline() for page in pages: pipe.lpush(key, "---NO PAGE YET---") await pipe.execute() bot.loop.create_task( update_pages(guild_id, query, fields, amount, pages, requested, longest_id, longest_type, longest_timestamp, header)) return len(pages)
async def test_filter_by_aggregation_field_with_or_not_reversed(self): tournament = await Tournament.create(name='0') await Tournament.create(name='1') await Tournament.create(name='2') await Event.create(name='1', tournament=tournament) tournaments = await Tournament.annotate(events_count=Count('events')).filter( ~(Q(name='2') | Q(events_count=1)), ) self.assertEqual(len(tournaments), 1) self.assertSetEqual({t.name for t in tournaments}, {'1'})
async def test_filter_by_aggregation_field_with_and_as_two_nodes(self): tournament = await Tournament.create(name='0') tournament_second = await Tournament.create(name='1') await Event.create(name='1', tournament=tournament) await Event.create(name='2', tournament=tournament_second) tournaments = await Tournament.annotate(events_count=Count('events')).filter( Q(events_count=1) & Q(name='0'), ) self.assertEqual(len(tournaments), 1) self.assertEqual(tournaments[0].id, tournament.id)