Skip to content

Commit 82d458c

Browse files
authored
Merge pull request #542 from kalombos/fix_per_page
limited per_page param in paginate
2 parents 35d2871 + 5cd3def commit 82d458c

File tree

3 files changed

+15
-1
lines changed

3 files changed

+15
-1
lines changed

CHANGES

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -12,7 +12,10 @@ In development
1212
by models. (`#551`_)
1313
- Raise the correct error when a model has a table name but no primary key.
1414
(`#556`_)
15+
- Allow specifying a ``max_per_page`` limit for pagination, to avoid users
16+
specifying high values in the request args. (`#542`_)
1517

18+
.. _#542: https://github.com/mitsuhiko/flask-sqlalchemy/pull/542
1619
.. _#551: https://github.com/mitsuhiko/flask-sqlalchemy/pull/551
1720
.. _#556: https://github.com/mitsuhiko/flask-sqlalchemy/pull/556
1821

flask_sqlalchemy/__init__.py

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -427,7 +427,7 @@ def first_or_404(self):
427427
abort(404)
428428
return rv
429429

430-
def paginate(self, page=None, per_page=None, error_out=True):
430+
def paginate(self, page=None, per_page=None, error_out=True, max_per_page=None):
431431
"""Returns ``per_page`` items from page ``page``.
432432
433433
If no items are found and ``page`` is greater than 1, or if page is
@@ -469,6 +469,9 @@ def paginate(self, page=None, per_page=None, error_out=True):
469469
if per_page is None:
470470
per_page = 20
471471

472+
if max_per_page is not None:
473+
per_page = min(per_page, max_per_page)
474+
472475
if error_out and page < 1:
473476
abort(404)
474477

tests/test_pagination.py

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -41,3 +41,11 @@ def index():
4141
# query default
4242
p = Todo.query.paginate()
4343
assert p.total == 100
44+
45+
46+
def test_query_paginate_more_than_20(app, db, Todo):
47+
with app.app_context():
48+
db.session.add_all(Todo('', '') for _ in range(20))
49+
db.session.commit()
50+
51+
assert len(Todo.query.paginate(max_per_page=10).items) == 10

0 commit comments

Comments
 (0)