跳转至

Helpers

get_filestorage_size(file)

A helper function to get the size of the FileStorage object in bytes.

Parameters:

Name Type Description Default
file FileStorage

A FileStorage object.

required

Version added: 2.1.0

Source code in apiflask/helpers.py
114
115
116
117
118
119
120
121
122
123
124
def get_filestorage_size(file: FileStorage) -> int:
    """A helper function to get the size of the FileStorage object in bytes.

    Arguments:
        file: A FileStorage object.

    *Version added: 2.1.0*
    """
    size = len(file.read())
    file.stream.seek(0)
    return size

get_reason_phrase(status_code, default='Unknown')

A helper function to get the reason phrase of the given status code.

Parameters:

Name Type Description Default
status_code int

A standard HTTP status code.

required
default str

The default phrase to use if not found, defaults to "Unknown".

'Unknown'

Version Changed: 0.6.0

  • Add default parameter.
Source code in apiflask/helpers.py
15
16
17
18
19
20
21
22
23
24
25
26
def get_reason_phrase(status_code: int, default: str = 'Unknown') -> str:
    """A helper function to get the reason phrase of the given status code.

    Arguments:
        status_code: A standard HTTP status code.
        default: The default phrase to use if not found, defaults to "Unknown".

    *Version Changed: 0.6.0*

    - Add `default` parameter.
    """
    return HTTP_STATUS_CODES.get(status_code, default)

pagination_builder(pagination, **kwargs)

A helper function to make pagination data.

This function is designed based on Flask-SQLAlchemy's Pagination class. If you are using a different or custom pagination class, make sure the passed pagination object has the following attributes:

  • page
  • per_page
  • pages
  • total
  • next_num
  • has_next
  • prev_num
  • has_prev

Or you can write your own builder function to build the pagination data.

Examples:

from apiflask import PaginationSchema, pagination_builder

...

class PetQuery(Schema):
    page = Integer(load_default=1)
    per_page = Integer(load_default=20, validate=Range(max=30))


class PetsOut(Schema):
    pets = List(Nested(PetOut))
    pagination = Nested(PaginationSchema)


@app.get('/pets')
@app.input(PetQuery, location='query')
@app.output(PetsOut)
def get_pets(query):
    pagination = PetModel.query.paginate(
        page=query['page'],
        per_page=query['per_page']
    )
    pets = pagination.items
    return {
        'pets': pets,
        'pagination': pagination_builder(pagination)
    }

See https://github.com/apiflask/apiflask/blob/main/examples/pagination/app.py for the complete example.

Parameters:

Name Type Description Default
pagination PaginationType

The pagination object.

required
**kwargs Any

Additional keyword arguments that passed to the url_for function when generate the page-related URLs.

{}

Version Added: 0.6.0

Source code in apiflask/helpers.py
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
def pagination_builder(pagination: PaginationType, **kwargs: t.Any) -> dict:
    """A helper function to make pagination data.

    This function is designed based on Flask-SQLAlchemy's `Pagination` class.
    If you are using a different or custom pagination class, make sure the
    passed pagination object has the following attributes:

    - page
    - per_page
    - pages
    - total
    - next_num
    - has_next
    - prev_num
    - has_prev

    Or you can write your own builder function to build the pagination data.

    Examples:

    ```python
    from apiflask import PaginationSchema, pagination_builder

    ...

    class PetQuery(Schema):
        page = Integer(load_default=1)
        per_page = Integer(load_default=20, validate=Range(max=30))


    class PetsOut(Schema):
        pets = List(Nested(PetOut))
        pagination = Nested(PaginationSchema)


    @app.get('/pets')
    @app.input(PetQuery, location='query')
    @app.output(PetsOut)
    def get_pets(query):
        pagination = PetModel.query.paginate(
            page=query['page'],
            per_page=query['per_page']
        )
        pets = pagination.items
        return {
            'pets': pets,
            'pagination': pagination_builder(pagination)
        }
    ```

    See <https://github.com/apiflask/apiflask/blob/main/examples/pagination/app.py>
    for the complete example.

    Arguments:
        pagination: The pagination object.
        **kwargs: Additional keyword arguments that passed to the
            `url_for` function when generate the page-related URLs.

    *Version Added: 0.6.0*
    """
    endpoint: t.Optional[str] = request.endpoint
    per_page: int = pagination.per_page

    def get_page_url(page: int) -> str:
        if endpoint is None:  # pragma: no cover
            return ''
        return url_for(
            endpoint, page=page, per_page=per_page, _external=True, **kwargs
        )

    next: str = get_page_url(pagination.next_num) if pagination.has_next else ''
    prev: str = get_page_url(pagination.prev_num) if pagination.has_prev else ''
    return {
        'total': pagination.total,
        'pages': pagination.pages,
        'per_page': per_page,
        'page': pagination.page,
        'next': next,
        'prev': prev,
        'first': get_page_url(1),
        'last': get_page_url(pagination.pages),
        'current': get_page_url(pagination.page),
    }

parse_size(size)

A helper function to parse a str representing the size into a number in bytes.

Parameters:

Name Type Description Default
size str

A str representing the size.

required

Version added: 2.1.0

Source code in apiflask/helpers.py
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
def parse_size(size: str) -> float:  # noqa: E302
    """A helper function to parse a str representing the size into a number in bytes.

    Arguments:
        size: A str representing the size.

    *Version added: 2.1.0*
    """
    size = size.strip()
    reg = re.compile(r'([e\+\-\.\d]+)\s*([kmgtpezy])?(i)?(b)', flags=re.I)

    match = reg.fullmatch(size)

    if not match:
        raise ValueError(f"Invalid size value: '{size!r}'")

    s, u, i, b = match.groups()

    try:
        s = float(s)
    except ValueError as e:
        raise ValueError(f"Invalid float value while parsing size: '{s!r}'") from e

    u = 'kmgtpezy'.index(u.lower()) + 1 if u else 0
    i = 1024 if i else 1000
    b = {'b': 8, 'B': 1}[b] if b else 1
    size: float = s * i**u / b

    return size