Fixed #7307 -- Split InvalidPage exception into two subclasses, PageNotAnInteger and EmptyPage, for granular exception catching. Thanks for the idea, miracle2k

git-svn-id: http://code.djangoproject.com/svn/django/trunk@7867 bcc190cf-cafb-0310-a4f2-bffc1f526a37
This commit is contained in:
Adrian Holovaty 2008-07-08 02:20:48 +00:00
parent cb70c99537
commit a724fff300
2 changed files with 26 additions and 5 deletions

View File

@ -1,6 +1,12 @@
class InvalidPage(Exception):
pass
class PageNotAnInteger(InvalidPage):
pass
class EmptyPage(InvalidPage):
pass
class Paginator(object):
def __init__(self, object_list, per_page, orphans=0, allow_empty_first_page=True):
self.object_list = object_list
@ -14,14 +20,14 @@ class Paginator(object):
try:
number = int(number)
except ValueError:
raise InvalidPage('That page number is not an integer')
raise PageNotAnInteger('That page number is not an integer')
if number < 1:
raise InvalidPage('That page number is less than 1')
raise EmptyPage('That page number is less than 1')
if number > self.num_pages:
if number == 1 and self.allow_empty_first_page:
pass
else:
raise InvalidPage('That page contains no results')
raise EmptyPage('That page contains no results')
return number
def page(self, number):
@ -129,14 +135,14 @@ class ObjectPaginator(Paginator):
try:
page_number = int(page_number) + 1
except ValueError:
raise InvalidPage
raise PageNotAnInteger
return self.validate_number(page_number)
def get_page(self, page_number):
try:
page_number = int(page_number) + 1
except ValueError:
raise InvalidPage
raise PageNotAnInteger
return self.page(page_number).object_list
def has_next_page(self, page_number):

View File

@ -82,6 +82,21 @@ Attributes
``page_range`` -- A 1-based range of page numbers, e.g., ``[1, 2, 3, 4]``.
``InvalidPage`` exceptions
==========================
The ``page()`` method raises ``InvalidPage`` if the requested page is invalid
(i.e., not an integer) or contains no objects. Generally, it's enough to trap
the ``InvalidPage`` exception, but if you'd like more granularity, you can trap
either of the following exceptions:
``PageNotAnInteger`` -- Raised when ``page()`` is given a value that isn't an integer.
``EmptyPage`` -- Raised when ``page()`` is given a valid value but no objects exist on that page.
Both of the exceptions are subclasses of ``InvalidPage``, so you can handle
them both with a simple ``except InvalidPage``.
``Page`` objects
================