示例#1
0
async def users(
    request: Request,
    res: Response,
    limit: Optional[int] = 20,
    offset: Optional[int] = 0,
    sort: Optional[str] = "id:asc",
) -> Optional[List[Dict[str, Any]]]:
    """Get all users or some of them using 'offset' and 'limit'

    Args:

        limit (int, optional): max number of returned users.
        Defaults to 100.
        offset (int, optional): first user 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:

        Optional[List[Dict[str, Any]]]: list of users found or
        Dict with error
    """
    response = {
        "success": False,
        "users": [],
    }
    order_by = API_functools.valid_order(Person, sort)
    if order_by is None:
        res.status_code = status.HTTP_400_BAD_REQUEST
        return {
            **response,
            "detail":
            "Invalid sort parameters. it must match \
            attribute:order. ex: id:asc or id:desc",
        }

    if offset < 0 or limit < 1:
        res.status_code = status.HTTP_400_BAD_REQUEST
        return {
            **response,
            "detail": "Invalid values: offset(>=0) or limit(>0)",
        }
    nb_users = await Person.all().count()

    users = await Person_Pydantic.from_queryset(
        Person.all().limit(limit).offset(offset).order_by(order_by))

    if len(users) == 0:
        res.status_code = status.HTTP_404_NOT_FOUND
        return {**response, "detail": "Not Found"}

    return API_functools.manage_next_previous_page(request, users, nb_users,
                                                   limit, offset)
示例#2
0
async def filter_comments(
    req: Request,
    res: Response,
    max_comments: int,
    data: Optional[list[dict]] = None,
    filters: Optional[dict] = None,
    offset: Optional[int] = 20,
    limit: Optional[int] = 0,
    sort: Optional[str] = "id:asc",
):

    response = {
        "success": False,
        "comments": [],
    }
    if data is None:
        order_by = API_functools.valid_order(Comment, sort)
        if order_by is None:
            res.status_code = status.HTTP_400_BAD_REQUEST
            return {
                **response,
                "detail": invalid_sort_detail,
            }

    if offset < 0 or limit < 1:
        res.status_code = status.HTTP_400_BAD_REQUEST
        return {
            **response,
            "detail": "Invalid values: offset(>=0) or limit(>0)",
        }
    if data is None:
        comments = await API_functools.add_owner_fullname(
            jsonable_encoder(await (
                Comment.all() if filters is None else Comment.filter(**filters)
            ).prefetch_related("vote").prefetch_related("children").annotate(
                votes=Count("vote", distinct=True)
            ).annotate(nb_children=Count("children", distinct=True)
                       ).limit(limit).offset(offset).order_by(order_by).values(
                           *API_functools.get_attributes(Comment), "votes",
                           "nb_children")))
    else:
        comments = data

    if len(comments) == 0:
        res.status_code = status.HTTP_404_NOT_FOUND
        return {**response, "detail": "Not Found"}
    return API_functools.manage_next_previous_page(req,
                                                   comments,
                                                   max_comments,
                                                   limit,
                                                   offset,
                                                   data_type="comments")
示例#3
0
 def test_manage_next_previous_page(self):
     scope = {"type": "http", "path": "/", "method": "GET"}
     request = Request(scope)
     scenes = [
         {
             "data": (0, 5, 0),  # nb_total_data, limit, offset
             "expected": {
                 "next": None,
                 "previous": None,
                 "success": False,
                 "users": [],
             },
         },
         {
             "data": (15, 5, 5),
             "expected": {
                 "next": "/?limit=5&offset=10",
                 "previous": "/?limit=5&offset=0",
                 "success": False,
                 "users": [],
             },
         },
         {
             "data": (10, 5, 0),
             "expected": {
                 "next": "/?limit=5&offset=5",
                 "previous": None,
                 "success": False,
                 "users": [],
             },
         },
         {
             "data": (10, 5, 5),
             "expected": {
                 "next": None,
                 "previous": "/?limit=5&offset=0",
                 "success": False,
                 "users": [],
             },
         },
     ]
     for scene in scenes:
         # scene 1 next=None, previous=None
         actual = API_functools.manage_next_previous_page(request, [],
                                                          *scene["data"],
                                                          data_type="users")
         assert actual == scene["expected"]