async def create_comment(res: Response, comment: dict) -> Dict[str, Any]:
    """Create new comment\n

    Args:\n
        comment (dict): Comment to create\n

    Returns:\n
        Dict[str, Any]: Comment created\n
    """
    data = {
        "success": True,
        "comment": {},
        "detail": "Comment successfully created",
    }
    comment_owner = API_functools.get_or_default(
        await Person.filter(pk=comment.get("user", 0)), 0, None)

    if comment_owner is None:
        res.status_code = status.HTTP_404_NOT_FOUND
        data["success"] = False
        data["detail"] = "Comment owner doesn't exist"
        return data
    comment["user"] = comment_owner
    data["comment"] = API_functools.tortoise_to_dict(await
                                                     Comment.create(**comment))
    return jsonable_encoder(data)
 def test_get_or_default(self):
     list_object = (
         {
             "name": "John Doe"
         },
         {
             "name": "Bob Doe"
         },
         {
             "name": "Alice Doe"
         },
     )
     for index, obj in enumerate(list_object):
         assert API_functools.get_or_default(list_object, index,
                                             None) == obj
     assert API_functools.get_or_default(list_object, len(list_object),
                                         None) is None
Exemple #3
0
async def users_by_ID(res: Response, user_ID: int) -> Dict[str, Any]:
    """Get user by ID

    Args:

        user_ID (int): user ID

    Returns:

        Dict[str, Any]: user found or Error
    """
    user = await Person_Pydantic.from_queryset(Person.filter(pk=user_ID))
    data = {
        "success": True,
        "user": API_functools.get_or_default(user, 0, {}),
    }
    if not API_functools.instance_of(data["user"], Person):
        res.status_code = status.HTTP_404_NOT_FOUND
        data["success"] = False
        data["detail"] = "Not Found"
    return data
async def comments_by_ID(
    req: Request,
    res: Response,
    comment_ID: int,
    children: bool = False,
    limit: Optional[int] = 20,
    offset: Optional[int] = 0,
    sort: Optional[str] = "id:asc",
) -> Dict[str, Any]:
    """Get comment by ID

    Args:

        comment_ID (int): comment ID
        children (bool): get current comment children
        limit (int, optional): max number of returned comments.
            Defaults to 100.
        offset (int, optional): first comment to return (use with limit).
            Defaults to 1.
        sort (str, optional): the order of the result.
            attribute:(asc {ascending} or desc {descending}). Defaults to "id:asc".

    Returns:

        Dict[str, Any]: contains comment found
    """
    key, value = ("comment", {}) if not children else ("comments", [])
    response = {"success": True, key: value, "detail": "Successful operation"}

    if not await Comment.exists(pk=comment_ID):
        res.status_code = status.HTTP_404_NOT_FOUND
        response["success"] = False
        response["detail"] = "Not Found"
        return response

    if children:
        order_by = API_functools.valid_order(Comment, sort)

        if order_by is None:
            res.status_code = status.HTTP_400_BAD_REQUEST
            return {
                **response,
                "success": False,
                "detail": invalid_sort_detail,
            }
        comment = await Comment.filter(pk=comment_ID).first()
        comments = await comment.json_children(order_by=order_by)
        response["comments"] = comments
        return await filter_comments(
            req,
            res,
            len(response["comments"]),
            data=response["comments"],
            offset=offset,
            limit=limit,
            sort=sort,
        )

    else:
        response["comment"] = API_functools.get_or_default(
            await API_functools.add_owner_fullname([
                API_functools.get_or_default(
                    jsonable_encoder(await Comment.filter(
                        pk=comment_ID
                    ).prefetch_related("vote").prefetch_related(
                        "children").annotate(
                            votes=Count("vote", distinct=True)
                        ).annotate(nb_children=Count("children", distinct=True)
                                   ).values(
                                       *API_functools.get_attributes(Comment),
                                       "votes",
                                       "nb_children",
                                   )),
                    index=0,
                    default={},
                )
            ]),
            index=0,
            default={},
        )

    return response