async def post(request: Request, ident): ident = ident.replace('+', ' ') if ident.isdigit(): post_data = await Post.cache(ident=int(ident)) else: post_data = await Post.get_by_slug(ident) if not post_data: raise HTMLResponse(status_code=404) post = Post(**post_data) stats = await post.stats reaction_type = None liked_comment_ids = [] github_user = request.session.get('github_user') pageview = await post.incr_pageview() related_posts = await post.get_related(limit=4) if github_user: reaction_type = await post.get_reaction_type(github_user['gid']) liked_comment_ids = await post.comment_ids_liked_by(github_user['gid']) post = await post.to_async_dict(**post_data) post.author = config.AttrDict(post.author) return { 'post': post, 'github_user': github_user, 'stats': stats, 'reaction_type': reaction_type, 'liked_comment_ids': liked_comment_ids, 'related_posts': related_posts, 'pageview': pageview }
async def page_(request: Request, ident): if isinstance(ident, str): post = await Post.get_by_slug(ident) if not post: raise HTMLResponse(status_code=404) post = await Post(**post).to_async_dict(**post) post.author = config.AttrDict(post.author) return {'post': post}
async def to_sync_dict(self): rv = self.to_dict() for field in self.property_fields: coro = getattr(self, field) if inspect.iscoroutine(coro) or (PY36 and isinstance( coro, CoroWrapper)): rv[field] = await coro else: rv[field] = coro rv['url'] = self.url return config.AttrDict(rv)
async def to_async_dict(self, **data): """some coroutine properties like `post.html_content` we have to use it like `await post.html_content` however if we use it in Mako template, we have to process it into the obj can use point access. """ rv = { key: value for key, value in data.items() } 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 config.AttrDict(rv)
async def index(request: Request, page=1): start = (page - 1) * config.PER_PAGE posts = await Post.get_all(with_page=False) total = len(posts) posts = posts[start:start + config.PER_PAGE] post_objs = [await Post(**p).to_async_dict(**p) for p in posts] paginatior = Pagination(page, config.PER_PAGE, total, post_objs) json = {'paginatior': paginatior} for partial in config.partials: partial = config.AttrDict(partial) if partial.name == 'tagcloud': tags = await _tags() random.shuffle(tags) json.update({'tags': tags}) return json