async def _posts(request: Request, page: int = 1): start = (page - 1) * PER_PAGE posts = await Post.get_all(with_page=False) total = len(posts) posts = posts[start: start + PER_PAGE] paginatior = Pagination(page, PER_PAGE, total, posts) json: Dict[ str, Union[List[Tuple[int, Post]], List[AttrDict], List[Tuple[Tag, int]], Pagination]] = {'paginatior': paginatior} for partial in partials: partial = AttrDict(partial) if partial.name == 'most_viewed': json.update({ 'most_viewed_posts': await get_most_viewed_posts( partial.count) }) elif partial.name == 'latest_comments': comments = await get_latest_comments(partial.count) latest_comments = [] for c in comments: user = await c.user post = await Post.cache(c.target_id) user = AttrDict({ 'name': user.username, 'link': user.link, 'avatar': user.picture, }) post = AttrDict({ 'title': post.title if post else '[已删除]', }) dct = { 'user': user, 'post': post, 'content': await c.content, 'date': c.created_at.strftime('%Y-%m-%d') } latest_comments.append(AttrDict(dct)) json.update({'latest_comments': latest_comments}) elif partial.name == 'tagcloud': tags = await _tags() random.shuffle(tags) json.update({'tags': tags}) return json
async def to_sync_dict(self): rv = self.to_dict() for field in self.property_fields: coro = getattr(self, field) if inspect.iscoroutine(coro): rv[field] = await coro else: rv[field] = coro rv['url'] = self.url return AttrDict(rv)