Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

limited per_page param in paginate #542

Merged
merged 2 commits into from
Oct 4, 2017
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 3 additions & 0 deletions CHANGES
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,10 @@ In development
by models. (`#551`_)
- Raise the correct error when a model has a table name but no primary key.
(`#556`_)
- Allow specifying a ``max_per_page`` limit for pagination, to avoid users
specifying high values in the request args. (`#542`_)

.. _#542: https://github.com/mitsuhiko/flask-sqlalchemy/pull/542
.. _#551: https://github.com/mitsuhiko/flask-sqlalchemy/pull/551
.. _#556: https://github.com/mitsuhiko/flask-sqlalchemy/pull/556

Expand Down
5 changes: 4 additions & 1 deletion flask_sqlalchemy/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -427,7 +427,7 @@ def first_or_404(self):
abort(404)
return rv

def paginate(self, page=None, per_page=None, error_out=True):
def paginate(self, page=None, per_page=None, error_out=True, max_per_page=None):
"""Returns ``per_page`` items from page ``page``.

If no items are found and ``page`` is greater than 1, or if page is
Expand Down Expand Up @@ -469,6 +469,9 @@ def paginate(self, page=None, per_page=None, error_out=True):
if per_page is None:
per_page = 20

if max_per_page is not None:
per_page = min(per_page, max_per_page)

if error_out and page < 1:
abort(404)

Expand Down
8 changes: 8 additions & 0 deletions tests/test_pagination.py
Original file line number Diff line number Diff line change
Expand Up @@ -41,3 +41,11 @@ def index():
# query default
p = Todo.query.paginate()
assert p.total == 100


def test_query_paginate_more_than_20(app, db, Todo):
with app.app_context():
db.session.add_all(Todo('', '') for _ in range(20))
db.session.commit()

assert len(Todo.query.paginate(max_per_page=10).items) == 10