pax_global_header00006660000000000000000000000064146626361350014526gustar00rootroot0000000000000052 comment=b02abe4a3b6cec7628ba7eebdabd4e4c57dcec4c Pylons-paginate-b02abe4/000077500000000000000000000000001466263613500152615ustar00rootroot00000000000000Pylons-paginate-b02abe4/.github/000077500000000000000000000000001466263613500166215ustar00rootroot00000000000000Pylons-paginate-b02abe4/.github/workflows/000077500000000000000000000000001466263613500206565ustar00rootroot00000000000000Pylons-paginate-b02abe4/.github/workflows/test.yml000066400000000000000000000016071466263613500223640ustar00rootroot00000000000000# This workflow will install Python dependencies, run tests and lint with a variety of Python versions # For more information see: https://docs.github.com/en/actions/automating-builds-and-tests/building-and-testing-python name: Python package on: push: branches: [ "master", "dev" ] pull_request: branches: [ "master", "dev" ] jobs: build: runs-on: ubuntu-latest strategy: fail-fast: false matrix: python-version: ["3.9", "3.10", "3.11", "3.12"] steps: - uses: actions/checkout@v4 - name: Set up Python ${{ matrix.python-version }} uses: actions/setup-python@v3 with: python-version: ${{ matrix.python-version }} - name: Install dependencies run: | python -m pip install --upgrade pip python -m pip install -e .[dev] - name: Test with pytest run: | pytest Pylons-paginate-b02abe4/.gitignore000066400000000000000000000000671466263613500172540ustar00rootroot00000000000000dist/ *.pyc *.komodoproject paginate.egg-info/ build/ Pylons-paginate-b02abe4/.travis.yml000066400000000000000000000006071466263613500173750ustar00rootroot00000000000000language: python sudo: false matrix: include: - python: 2.7 env: TOXENV=py27 - python: 3.4 env: TOXENV=py34 - python: 3.5 env: TOXENV=py35 - python: pypy env: TOXENV=pypy - python: 3.6 env: TOXENV=py36 LINT=1 - python: nightly env: TOXENV=py37 allow_failures: - env: TOXENV=py37 install: - travis_retry pip install tox script: - travis_retry tox Pylons-paginate-b02abe4/CHANGELOG.txt000066400000000000000000000054031466263613500173130ustar00rootroot00000000000000Version 0.5.6 - 2016-11-22 -------------------------- Changes: - Fixed metadata for pypi Version 0.5.5 - 2016-11-22 -------------------------- Changes: - Python 2.7/3.4+ compatibility improvements Version 0.5.4 - 2016-04-25 -------------------------- Changes: - Added radius size config option Version 0.5.3 - 2016-03-09 -------------------------- Changes: - Unocode related fixes Version 0.5.2 - 2015-08-29 -------------------------- Changes: - Handle the slice prior to handling the length - for better experience with various databases that include item count in results - bugfixes Version 0.5.1 - 2015-10-22 -------------------------- Changes: - bugfixes Version 0.5.0 - 2015-08-29 -------------------------- Changes: - link_tag callable can now be passed to generate custom link markup - page object now has link_map() method that returns a mapping of information useful for generating custom markup based on paginator data Version 0.4.0 - 2012-12-06 -------------------------- Paginate has prior been maintained as webhelpers.paginate in the _webhelpers_ packages. This version is a standalone version that should be useful outside of the webhelpers' context. Changes: - Python 3 compatibility. - SQLAlchemyObject and SQLAlchemyQuery collections are not automatically detected any more. Instead you can use the respective Page class from the paginate_sqlalchemy module also available on PyPi. - presliced_list parameter no longer supported - 'page_nr' and 'current_page' had been deprecated already and are now removed. Please use 'page' instead. - No automatic URL generation. You need to pass a 'url' argument to the Page.pager() method containing a $page placeholder where you want the page number to be put in. Beware that the URL is not quote-escaped any further. - The Page.pager() does not automatically add CSS classes any more. If you want the old behavior you need to pass these parameters explicitly: link_attr={'class':'pager_link'} curpage_attr={'class':'pager_curpage'} dotdot_attr={'class':'pager_dotdot'} - The partial_param parameter from Page.pager() is gone. You should use your own URLs for AJAX/partial updates in the 'url' parameter. - The page_param parameter from Page.pager() is also gone as URL generation has been severely simplified. - The string returned from Page.pager() consists of escaped HTML already. So you need to tell your web framework to use the string verbatim and without further escaping. The parameters symbol_first, symbol_last, symbol_previous and symbol_next use < and > instead of "<" and ">" now. - Page.__repr__ now returns a brief representation. E.g. Page.__str__ returns the verbose view you may be used to. Version 0.3.2 - 2008-01-31 -------------------------- Public release on PyPi Pylons-paginate-b02abe4/LICENSE000066400000000000000000000021011466263613500162600ustar00rootroot00000000000000Copyright (c) 2007-2012 Christoph Haas Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. Pylons-paginate-b02abe4/MANIFEST000066400000000000000000000001531466263613500164110ustar00rootroot00000000000000# file GENERATED by distutils, do NOT edit README.txt setup.py paginate/__init__.py tests/test_paginate.py Pylons-paginate-b02abe4/MANIFEST.in000066400000000000000000000001771466263613500170240ustar00rootroot00000000000000include *.txt *.ini *.cfg *.rst *.md recursive-include *.ico *.png *.css *.gif *.jpg *.pt *.txt *.mak *.mako *.js *.html *.xml Pylons-paginate-b02abe4/README.md000066400000000000000000000170371466263613500165500ustar00rootroot00000000000000What is pagination? --------------------- This module helps dividing large lists of items into pages. The user is shown one page at a time and can navigate to other pages. Imagine you are offering a company phonebook and let the user search the entries. If the search result contains 23 entries but you may want to display no more than 10 entries at once. The first page contains entries 1-10, the second 11-20 and the third 21-23. See the documentation of the "Page" class for more information. How do I use this module? --------------------------- The paginate module contains extensive in-line documentation with examples. Concerning WebHelpers ----------------------- This is a standalone module. Former versions were included in the WebHelpers Python module as webhelpers.paginate and were tightly coupled with the WebHelpers and the Pylons web framework. This version aims to be useful independent of any web framework. Subclassing Page() ------------------ This module supports pagination through list-like objects. To paginate though other types of objects you can subclass the paginate.Page() class and provide a wrapper class that defines how to access elements of that special collection. You can find examples in other paginate_* modules like paginate_sqlalchemy. Basically you would have to provide a class that implements the __init__, __getitem__ and __len__ methods. It is trivial to make pagination for other datastores like Elasticsearch/Solr extending the base class. Example:: class SqlalchemyOrmWrapper(object): """Wrapper class to access elements of a collection.""" def __init__(self, obj): self.obj = obj def __getitem__(self, range): # Return a range of objects of an sqlalchemy.orm.query.Query object return self.obj[range] def __len__(self): # Count the number of objects in an sqlalchemy.orm.query.Query object return self.obj.count() Then you can create your own Page class that uses the above wrapper class:: class SqlalchemyOrmPage(paginate.Page): """A pagination page that deals with SQLAlchemy ORM objects.""" def __init__(self, *args, **kwargs): super(SqlalchemyOrmPage, self).__init__(*args, wrapper_class=SqlalchemyOrmWrapper, **kwargs) As you can see it does not do much. It basically calls paginate.Page.__init__ and adds wrapper_class=SqlalchemyOrmWrapper as an argument. The paginate.Page instance will use that wrapper class to access the elements. Generating HTML code for current page ------------------------------------- Example:: p = paginate.Page([], page=15, items_per_page=15, item_count=1010) # item_count is optional, but we pass a dummy empty resultset for this example pattern = '$link_first $link_previous ~4~ $link_next $link_last (Page $page our of $page_count - total $item_count)' p.pager(pattern, url='http://foo.com?x=$page', dotdot_attr={'x':5}, link_attr={'y':6}, curpage_attr={'z':77}) # *_attr arguments are optional and can be used to attach additional classes/attrs to tags Results in:: '<< < 1 .. 11 12 13 14 15 16 17 18 19 .. 68 > >> (Page 15 our of 68 - total items 1010)' Using url maker to generate links to specific result ranges ----------------------------------------------------------- You can pass `url_maker` Callback to generate the URL of other pages, given its numbers. Must accept one int parameter and return a URI string. Example:: def url_maker(page_number): return str('foo/%s' % page_number) page = paginate.Page(range(100), page=1, url_maker=url_maker) eq_(page.pager(), '1 2 3 .. 5') Alternatively if you will not pass the link builder function, the pager() method can also accept `url` argument that contains URL that page links will point to. Make sure it contains the string $page which will be replaced by the actual page number. Must be given unless a url_maker is specified to __init__, in which case this parameter is ignored. Using link information for custom paginator templates ----------------------------------------------------- If you do not like the default HTML format produced by paginator you can use link_map() function to generate a dictionary of links you can use in your own template. Example:: p.link_map('$link_first $link_previous ~4~ $link_next $link_last (Page $page our of $page_count - total items $item_count)',url='URL?x=$page',dotdot_attr={'class':'D'}, link_attr={'class':"L"}, curpage_attr={'class':"C"}) Returns something like:: {'current_page': {'attrs': {'class': 'C'}, 'href': 'URL?x=15', 'value': 15}, 'first_page': {'attrs': {'class': 'L'}, 'href': 'URL?x=1', 'type': 'first_page', 'value': 1}, 'last_page': {'attrs': {'class': 'L'}, 'href': 'URL?x=68', 'type': 'last_page', 'value': 68}, 'next_page': {'attrs': {'class': 'L'}, 'href': 'URL?x=16', 'type': 'next_page', 'value': 16}, 'previous_page': {'attrs': {'class': 'L'}, 'href': 'URL?x=14', 'type': 'previous_page', 'value': 14}, 'range_pages': [{'attrs': {'class': 'D'}, 'href': '', 'type': 'span', 'value': '..'}, {'attrs': {'class': 'L'}, 'href': 'URL?x=11', 'type': 'page', 'value': '11'}, {'attrs': {'class': 'L'}, 'href': 'URL?x=12', 'type': 'page', 'value': '12'}, {'attrs': {'class': 'L'}, 'href': 'URL?x=13', 'type': 'page', 'value': '13'}, {'attrs': {'class': 'L'}, 'href': 'URL?x=14', 'type': 'page', 'value': '14'}, {'attrs': {'class': 'C'}, 'href': 'URL?x=15', 'type': 'current_page', 'value': 15}, {'attrs': {'class': 'L'}, 'href': 'URL?x=16', 'type': 'page', 'value': '16'}, {'attrs': {'class': 'L'}, 'href': 'URL?x=17', 'type': 'page', 'value': '17'}, {'attrs': {'class': 'L'}, 'href': 'URL?x=18', 'type': 'page', 'value': '18'}, {'attrs': {'class': 'L'}, 'href': 'URL?x=19', 'type': 'page', 'value': '19'}, {'attrs': {'class': 'D'}, 'href': '', 'type': 'span', 'value': '..'}], 'radius': 4} Using link_tag callable to generate custom link markup ------------------------------------------------------ In case you want to generate custom link markup for your project - for example for use with bootstrap, `pager()` accepts `link_tag` argument that expects a callable that can be used to easily override the way links are generated. Example:: from paginate import Page, make_html_tag def paginate_link_tag(item): """ Create an A-HREF tag that points to another page usable in paginate. """ a_tag = Page.default_link_tag(item) if item['type'] == 'current_page': return make_html_tag('li', a_tag, **{'class':'active'}) return make_html_tag('li', a_tag) paginator.pager( curpage_attr={'class':'current_page'}, dotdot_attr={'class':'spacer'}, symbol_first='', symbol_last='', symbol_previous='', symbol_next='', link_tag=paginate_link_tag) Pylons-paginate-b02abe4/TODO000066400000000000000000000072221466263613500157540ustar00rootroot00000000000000Prepare proper documentation and examples for GitHub/readthedocs Prepare a method that can be overriden for extension modules like paginate-sqlalchemy (e.g. get_wrapper) Move SQLAlchemy code into a separate module paginate-sqlalchemy and subclass paginate.Page() for that purpose. Upload to PyPi Announce to pylons-discussion mailing list. Add AJAX tutorial onclick (optional) This paramter is a string containing optional Javascript code that will be used as the 'onclick' action of each pager link. It can be used to enhance your pager with AJAX actions loading another page into a DOM object. In this string the variable '$partial_url' will be replaced by the URL linking to the desired page with an added 'partial=1' parameter (or whatever you set 'partial_param' to). In addition the '$page' variable gets replaced by the respective page number. Note that the URL to the destination page contains a 'partial_param' parameter so that you can distinguish between AJAX requests (just refreshing the paginated area of your page) and full requests (loading the whole new page). [Backward compatibility: you can use '%s' instead of '$partial_url'] jQuery example: "$('#my-page-area').load('$partial_url'); return false;" Yahoo UI example: "YAHOO.util.Connect.asyncRequest('GET','$partial_url',{ success:function(o){YAHOO.util.Dom.get('#my-page-area').innerHTML=o.responseText;} },null); return false;" scriptaculous example: "new Ajax.Updater('#my-page-area', '$partial_url', {asynchronous:true, evalScripts:true}); return false;" ExtJS example: "Ext.get('#my-page-area').load({url:'$partial_url'}); return false;" Custom example: "my_load_page($page)" p.pager(url="/index.php?page=$page", link_attr=dict(onclick="$('target').load('/ding/dong?page=$page'")) Write SQLAlchemy tests Create test with setup/teardown code for paginate.sqlalchemy.SqlalchemyPage (e.g. sqlite) #class TestSQLAlchemyCollectionTypes(unittest.TestCase): # def setUp(self): # try: # import sqlalchemy as sa # import sqlalchemy.orm as orm # except ImportError: # raise SkipTest() # self.engine = engine = sa.create_engine("sqlite://") # Memory database # self.sessionmaker = orm.sessionmaker(bind=engine) # self.metadata = metadata = sa.MetaData(bind=engine) # self.notes = notes = sa.Table("Notes", metadata, # sa.Column("id", sa.Integer, primary_key=True)) # class Note(object): # pass # self.Note = Note # notes.create() # orm.mapper(Note, notes) # insert = notes.insert() # records = [{"id": x} for x in range(1, 101)] # engine.execute(insert, records) # # def tearDown(self): # import sqlalchemy as sa # import sqlalchemy.orm as orm # orm.clear_mappers() # self.notes.drop() # # def test_sqlalchemy_orm(self): # session = self.sessionmaker() # q = session.query(self.Note).order_by(self.Note.id) # page = paginate.Page(q) # records = list(page) # eq_(records[0].id, 1) # eq_(records[-1].id, 20) add support for CouchDB databases (http://guide.couchdb.org/editions/1/de/recipes.html) careful: CouchDB is stupid and has very limited and weird behavior when it comes to choosing a certain page of data Pylons-paginate-b02abe4/paginate.egg-info/000077500000000000000000000000001466263613500205435ustar00rootroot00000000000000Pylons-paginate-b02abe4/paginate.egg-info/top_level.txt000066400000000000000000000000111466263613500232650ustar00rootroot00000000000000paginate Pylons-paginate-b02abe4/paginate/000077500000000000000000000000001466263613500170515ustar00rootroot00000000000000Pylons-paginate-b02abe4/paginate/__init__.py000066400000000000000000000763111466263613500211720ustar00rootroot00000000000000# Copyright (c) 2007-2012 Christoph Haas # See the file LICENSE for copying permission. """ paginate: helps split up large collections into individual pages ================================================================ What is pagination? --------------------- This module helps split large lists of items into pages. The user is shown one page at a time and can navigate to other pages. Imagine you are offering a company phonebook and let the user search the entries. The entire search result may contains 23 entries but you want to display no more than 10 entries at once. The first page contains entries 1-10, the second 11-20 and the third 21-23. Each "Page" instance represents the items of one of these three pages. See the documentation of the "Page" class for more information. How do I use it? ------------------ A page of items is represented by the *Page* object. A *Page* gets initialized with these arguments: - The collection of items to pick a range from. Usually just a list. - The page number you want to display. Default is 1: the first page. Now we can make up a collection and create a Page instance of it:: # Create a sample collection of 1000 items >> my_collection = range(1000) # Create a Page object for the 3rd page (20 items per page is the default) >> my_page = Page(my_collection, page=3) # The page object can be printed as a string to get its details >> str(my_page) Page: Collection type: Current page: 3 First item: 41 Last item: 60 First page: 1 Last page: 50 Previous page: 2 Next page: 4 Items per page: 20 Number of items: 1000 Number of pages: 50 # Print a list of items on the current page >> my_page.items [40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59] # The *Page* object can be used as an iterator: >> for my_item in my_page: print(my_item) 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 # The .pager() method returns an HTML fragment with links to surrounding pages. >> my_page.pager(url="http://example.org/foo/page=$page") 1 2 3 4 5 .. 50' # Without the HTML it would just look like: # 1 2 [3] 4 5 .. 50 # The pager can be customized: >> my_page.pager('$link_previous ~3~ $link_next (Page $page of $page_count)', url="http://example.org/foo/page=$page") < 1 2 3 4 5 6 .. 50 > (Page 3 of 50) # Without the HTML it would just look like: # 1 2 [3] 4 5 6 .. 50 > (Page 3 of 50) # The url argument to the pager method can be omitted when an url_maker is # given during instantiation: >> my_page = Page(my_collection, page=3, url_maker=lambda p: "http://example.org/%s" % p) >> page.pager() There are some interesting parameters that customize the Page's behavior. See the documentation on ``Page`` and ``Page.pager()``. Notes ------- Page numbers and item numbers start at 1. This concept has been used because users expect that the first page has number 1 and the first item on a page also has number 1. So if you want to use the page's items by their index number please note that you have to subtract 1. """ __author__ = "Christoph Haas" __copyright__ = "Copyright 2007-2016 Christoph Haas and contributors" __credits__ = ["Mike Orr"] __license__ = "MIT" __version__ = "0.5.4" __maintainer__ = "Marcin Lulek, Luke Crooks" __email__ = "info@webreactor.eu, luke@pumalo.org" __status__ = "Beta" import re from string import Template import sys # are we running at least python 3.x ? PY3 = sys.version_info[0] >= 3 if PY3: unicode = str # Since the items on a page are mainly a list we subclass the "list" type class Page(list): """A list/iterator representing the items on one page of a larger collection. An instance of the "Page" class is created from a _collection_ which is any list-like object that allows random access to its elements. The instance works as an iterator running from the first item to the last item on the given page. The Page.pager() method creates a link list allowing the user to go to other pages. A "Page" does not only carry the items on a certain page. It gives you additional information about the page in these "Page" object attributes: item_count Number of items in the collection **WARNING:** Unless you pass in an item_count, a count will be performed on the collection every time a Page instance is created. page Number of the current page items_per_page Maximal number of items displayed on a page first_page Number of the first page - usually 1 :) last_page Number of the last page previous_page Number of the previous page. If this is the first page it returns None. next_page Number of the next page. If this is the last page it returns None. page_count Number of pages items Sequence/iterator of items on the current page first_item Index of first item on the current page - starts with 1 last_item Index of last item on the current page """ def __init__( self, collection, page=1, items_per_page=20, item_count=None, wrapper_class=None, url_maker=None, **kwargs ): """Create a "Page" instance. Parameters: collection Sequence representing the collection of items to page through. page The requested page number - starts with 1. Default: 1. items_per_page The maximal number of items to be displayed per page. Default: 20. item_count (optional) The total number of items in the collection - if known. If this parameter is not given then the paginator will count the number of elements in the collection every time a "Page" is created. Giving this parameter will speed up things. In a busy real-life application you may want to cache the number of items. url_maker (optional) Callback to generate the URL of other pages, given its numbers. Must accept one int parameter and return a URI string. """ if collection is not None: if wrapper_class is None: # Default case. The collection is already a list-type object. self.collection = collection else: # Special case. A custom wrapper class is used to access elements of the collection. self.collection = wrapper_class(collection) else: self.collection = [] self.collection_type = type(collection) if url_maker is not None: self.url_maker = url_maker else: self.url_maker = self._default_url_maker # Assign kwargs to self self.kwargs = kwargs # The self.page is the number of the current page. # The first page has the number 1! try: self.page = int(page) # make it int() if we get it as a string except (ValueError, TypeError): self.page = 1 # normally page should be always at least 1 but the original maintainer # decided that for empty collection and empty page it can be...0? (based on tests) # preserving behavior for BW compat if self.page < 1: self.page = 1 self.items_per_page = items_per_page # We subclassed "list" so we need to call its init() method # and fill the new list with the items to be displayed on the page. # We use list() so that the items on the current page are retrieved # only once. In an SQL context that could otherwise lead to running the # same SQL query every time items would be accessed. # We do this here, prior to calling len() on the collection so that a # wrapper class can execute a query with the knowledge of what the # slice will be (for efficiency) and, in the same query, ask for the # total number of items and only execute one query. try: first = (self.page - 1) * items_per_page last = first + items_per_page self.items = list(self.collection[first:last]) except (KeyError, TypeError) as exc: raise TypeError( "Your collection of type {} cannot be handled " "by paginate.".format(type(self.collection)) ) # Unless the user tells us how many items the collections has # we calculate that ourselves. if item_count is not None: self.item_count = item_count else: self.item_count = len(self.collection) # Compute the number of the first and last available page if self.item_count > 0: self.first_page = 1 self.page_count = ((self.item_count - 1) // self.items_per_page) + 1 self.last_page = self.first_page + self.page_count - 1 # Make sure that the requested page number is the range of valid pages if self.page > self.last_page: self.page = self.last_page elif self.page < self.first_page: self.page = self.first_page # Note: the number of items on this page can be less than # items_per_page if the last page is not full self.first_item = (self.page - 1) * items_per_page + 1 self.last_item = min(self.first_item + items_per_page - 1, self.item_count) # Links to previous and next page if self.page > self.first_page: self.previous_page = self.page - 1 else: self.previous_page = None if self.page < self.last_page: self.next_page = self.page + 1 else: self.next_page = None # No items available else: self.first_page = None self.page_count = 0 self.last_page = None self.first_item = None self.last_item = None self.previous_page = None self.next_page = None self.items = [] # This is a subclass of the 'list' type. Initialise the list now. list.__init__(self, self.items) def __str__(self): return ( "Page:\n" "Collection type: {0.collection_type}\n" "Current page: {0.page}\n" "First item: {0.first_item}\n" "Last item: {0.last_item}\n" "First page: {0.first_page}\n" "Last page: {0.last_page}\n" "Previous page: {0.previous_page}\n" "Next page: {0.next_page}\n" "Items per page: {0.items_per_page}\n" "Total number of items: {0.item_count}\n" "Number of pages: {0.page_count}\n" ).format(self) def __repr__(self): return "".format(self.page, self.page_count) def pager( self, format="~2~", url=None, show_if_single_page=False, separator=" ", symbol_first="<<", symbol_last=">>", symbol_previous="<", symbol_next=">", link_attr=None, curpage_attr=None, dotdot_attr=None, link_tag=None, ): """ Return string with links to other pages (e.g. '1 .. 5 6 7 [8] 9 10 11 .. 50'). format: Format string that defines how the pager is rendered. The string can contain the following $-tokens that are substituted by the string.Template module: - $first_page: number of first reachable page - $last_page: number of last reachable page - $page: number of currently selected page - $page_count: number of reachable pages - $items_per_page: maximal number of items per page - $first_item: index of first item on the current page - $last_item: index of last item on the current page - $item_count: total number of items - $link_first: link to first page (unless this is first page) - $link_last: link to last page (unless this is last page) - $link_previous: link to previous page (unless this is first page) - $link_next: link to next page (unless this is last page) To render a range of pages the token '~3~' can be used. The number sets the radius of pages around the current page. Example for a range with radius 3: '1 .. 5 6 7 [8] 9 10 11 .. 50' Default: '~2~' url The URL that page links will point to. Make sure it contains the string $page which will be replaced by the actual page number. Must be given unless a url_maker is specified to __init__, in which case this parameter is ignored. symbol_first String to be displayed as the text for the $link_first link above. Default: '<<' (<<) symbol_last String to be displayed as the text for the $link_last link above. Default: '>>' (>>) symbol_previous String to be displayed as the text for the $link_previous link above. Default: '<' (<) symbol_next String to be displayed as the text for the $link_next link above. Default: '>' (>) separator: String that is used to separate page links/numbers in the above range of pages. Default: ' ' show_if_single_page: if True the navigator will be shown even if there is only one page. Default: False link_attr (optional) A dictionary of attributes that get added to A-HREF links pointing to other pages. Can be used to define a CSS style or class to customize the look of links. Example: { 'style':'border: 1px solid green' } Example: { 'class':'pager_link' } curpage_attr (optional) A dictionary of attributes that get added to the current page number in the pager (which is obviously not a link). If this dictionary is not empty then the elements will be wrapped in a SPAN tag with the given attributes. Example: { 'style':'border: 3px solid blue' } Example: { 'class':'pager_curpage' } dotdot_attr (optional) A dictionary of attributes that get added to the '..' string in the pager (which is obviously not a link). If this dictionary is not empty then the elements will be wrapped in a SPAN tag with the given attributes. Example: { 'style':'color: #808080' } Example: { 'class':'pager_dotdot' } link_tag (optional) A callable that accepts single argument `page` (page link information) and generates string with html that represents the link for specific page. Page objects are supplied from `link_map()` so the keys are the same. """ link_attr = link_attr or {} curpage_attr = curpage_attr or {} dotdot_attr = dotdot_attr or {} self.curpage_attr = curpage_attr self.separator = separator self.link_attr = link_attr self.dotdot_attr = dotdot_attr self.url = url self.link_tag = link_tag or self.default_link_tag # Don't show navigator if there is no more than one page if self.page_count == 0 or (self.page_count == 1 and not show_if_single_page): return "" regex_res = re.search(r"~(\d+)~", format) if regex_res: radius = regex_res.group(1) else: radius = 2 radius = int(radius) self.radius = radius link_map = self.link_map( format=format, url=url, show_if_single_page=show_if_single_page, separator=separator, symbol_first=symbol_first, symbol_last=symbol_last, symbol_previous=symbol_previous, symbol_next=symbol_next, link_attr=link_attr, curpage_attr=curpage_attr, dotdot_attr=dotdot_attr, ) links_markup = self._range(link_map, radius) # Replace ~...~ in token format by range of pages result = re.sub(r"~(\d+)~", links_markup, format) link_first = ( self.page > self.first_page and self.link_tag(link_map["first_page"]) or "" ) link_last = ( self.page < self.last_page and self.link_tag(link_map["last_page"]) or "" ) link_previous = ( self.previous_page and self.link_tag(link_map["previous_page"]) or "" ) link_next = self.next_page and self.link_tag(link_map["next_page"]) or "" # Interpolate '$' variables result = Template(result).safe_substitute( { "first_page": self.first_page, "last_page": self.last_page, "page": self.page, "page_count": self.page_count, "items_per_page": self.items_per_page, "first_item": self.first_item, "last_item": self.last_item, "item_count": self.item_count, "link_first": link_first, "link_last": link_last, "link_previous": link_previous, "link_next": link_next, } ) return result def link_map( self, format="~2~", url=None, show_if_single_page=False, separator=" ", symbol_first="<<", symbol_last=">>", symbol_previous="<", symbol_next=">", link_attr=None, curpage_attr=None, dotdot_attr=None, ): """ Return map with links to other pages if default pager() function is not suitable solution. format: Format string that defines how the pager would be normally rendered rendered. Uses same arguments as pager() method, but returns a simple dictionary in form of: {'current_page': {'attrs': {}, 'href': 'http://example.org/foo/page=1', 'value': 1}, 'first_page': {'attrs': {}, 'href': 'http://example.org/foo/page=1', 'type': 'first_page', 'value': 1}, 'last_page': {'attrs': {}, 'href': 'http://example.org/foo/page=8', 'type': 'last_page', 'value': 8}, 'next_page': {'attrs': {}, 'href': 'HREF', 'type': 'next_page', 'value': 2}, 'previous_page': None, 'range_pages': [{'attrs': {}, 'href': 'http://example.org/foo/page=1', 'type': 'current_page', 'value': 1}, .... {'attrs': {}, 'href': '', 'type': 'span', 'value': '..'}]} The string can contain the following $-tokens that are substituted by the string.Template module: - $first_page: number of first reachable page - $last_page: number of last reachable page - $page: number of currently selected page - $page_count: number of reachable pages - $items_per_page: maximal number of items per page - $first_item: index of first item on the current page - $last_item: index of last item on the current page - $item_count: total number of items - $link_first: link to first page (unless this is first page) - $link_last: link to last page (unless this is last page) - $link_previous: link to previous page (unless this is first page) - $link_next: link to next page (unless this is last page) To render a range of pages the token '~3~' can be used. The number sets the radius of pages around the current page. Example for a range with radius 3: '1 .. 5 6 7 [8] 9 10 11 .. 50' Default: '~2~' url The URL that page links will point to. Make sure it contains the string $page which will be replaced by the actual page number. Must be given unless a url_maker is specified to __init__, in which case this parameter is ignored. symbol_first String to be displayed as the text for the $link_first link above. Default: '<<' (<<) symbol_last String to be displayed as the text for the $link_last link above. Default: '>>' (>>) symbol_previous String to be displayed as the text for the $link_previous link above. Default: '<' (<) symbol_next String to be displayed as the text for the $link_next link above. Default: '>' (>) separator: String that is used to separate page links/numbers in the above range of pages. Default: ' ' show_if_single_page: if True the navigator will be shown even if there is only one page. Default: False link_attr (optional) A dictionary of attributes that get added to A-HREF links pointing to other pages. Can be used to define a CSS style or class to customize the look of links. Example: { 'style':'border: 1px solid green' } Example: { 'class':'pager_link' } curpage_attr (optional) A dictionary of attributes that get added to the current page number in the pager (which is obviously not a link). If this dictionary is not empty then the elements will be wrapped in a SPAN tag with the given attributes. Example: { 'style':'border: 3px solid blue' } Example: { 'class':'pager_curpage' } dotdot_attr (optional) A dictionary of attributes that get added to the '..' string in the pager (which is obviously not a link). If this dictionary is not empty then the elements will be wrapped in a SPAN tag with the given attributes. Example: { 'style':'color: #808080' } Example: { 'class':'pager_dotdot' } """ link_attr = link_attr or {} curpage_attr = curpage_attr or {} dotdot_attr = dotdot_attr or {} self.curpage_attr = curpage_attr self.separator = separator self.link_attr = link_attr self.dotdot_attr = dotdot_attr self.url = url regex_res = re.search(r"~(\d+)~", format) if regex_res: radius = regex_res.group(1) else: radius = 2 radius = int(radius) self.radius = radius # Compute the first and last page number within the radius # e.g. '1 .. 5 6 [7] 8 9 .. 12' # -> leftmost_page = 5 # -> rightmost_page = 9 leftmost_page = ( max(self.first_page, (self.page - radius)) if self.first_page else None ) rightmost_page = ( min(self.last_page, (self.page + radius)) if self.last_page else None ) nav_items = { "first_page": None, "last_page": None, "previous_page": None, "next_page": None, "current_page": None, "radius": self.radius, "range_pages": [], } if leftmost_page is None or rightmost_page is None: return nav_items nav_items["first_page"] = { "type": "first_page", "value": unicode(symbol_first), "attrs": self.link_attr, "number": self.first_page, "href": self.url_maker(self.first_page), } # Insert dots if there are pages between the first page # and the currently displayed page range if leftmost_page - self.first_page > 1: # Wrap in a SPAN tag if dotdot_attr is set nav_items["range_pages"].append( { "type": "span", "value": "..", "attrs": self.dotdot_attr, "href": "", "number": None, } ) for thispage in range(leftmost_page, rightmost_page + 1): # Highlight the current page number and do not use a link if thispage == self.page: # Wrap in a SPAN tag if curpage_attr is set nav_items["range_pages"].append( { "type": "current_page", "value": unicode(thispage), "number": thispage, "attrs": self.curpage_attr, "href": self.url_maker(thispage), } ) nav_items["current_page"] = { "value": thispage, "attrs": self.curpage_attr, "type": "current_page", "href": self.url_maker(thispage), } # Otherwise create just a link to that page else: nav_items["range_pages"].append( { "type": "page", "value": unicode(thispage), "number": thispage, "attrs": self.link_attr, "href": self.url_maker(thispage), } ) # Insert dots if there are pages between the displayed # page numbers and the end of the page range if self.last_page - rightmost_page > 1: # Wrap in a SPAN tag if dotdot_attr is set nav_items["range_pages"].append( { "type": "span", "value": "..", "attrs": self.dotdot_attr, "href": "", "number": None, } ) # Create a link to the very last page (unless we are on the last # page or there would be no need to insert '..' spacers) nav_items["last_page"] = { "type": "last_page", "value": unicode(symbol_last), "attrs": self.link_attr, "href": self.url_maker(self.last_page), "number": self.last_page, } nav_items["previous_page"] = { "type": "previous_page", "value": unicode(symbol_previous), "attrs": self.link_attr, "number": self.previous_page or self.first_page, "href": self.url_maker(self.previous_page or self.first_page), } nav_items["next_page"] = { "type": "next_page", "value": unicode(symbol_next), "attrs": self.link_attr, "number": self.next_page or self.last_page, "href": self.url_maker(self.next_page or self.last_page), } return nav_items def _range(self, link_map, radius): """ Return range of linked pages to substitute placeholder in pattern """ leftmost_page = max(self.first_page, (self.page - radius)) rightmost_page = min(self.last_page, (self.page + radius)) nav_items = [] # Create a link to the first page (unless we are on the first page # or there would be no need to insert '..' spacers) if self.page != self.first_page and self.first_page < leftmost_page: page = link_map["first_page"].copy() page["value"] = unicode(page["number"]) nav_items.append(self.link_tag(page)) for item in link_map["range_pages"]: nav_items.append(self.link_tag(item)) # Create a link to the very last page (unless we are on the last # page or there would be no need to insert '..' spacers) if self.page != self.last_page and rightmost_page < self.last_page: page = link_map["last_page"].copy() page["value"] = unicode(page["number"]) nav_items.append(self.link_tag(page)) return self.separator.join(nav_items) def _default_url_maker(self, page_number): if self.url is None: raise Exception( "You need to specify a 'url' parameter containing a '$page' placeholder." ) if "$page" not in self.url: raise Exception("The 'url' parameter must contain a '$page' placeholder.") return self.url.replace("$page", unicode(page_number)) @staticmethod def default_link_tag(item): """ Create an A-HREF tag that points to another page. """ text = item["value"] target_url = item["href"] if not item["href"] or item["type"] in ("span", "current_page"): if item["attrs"]: text = make_html_tag("span", **item["attrs"]) + text + "" return text return make_html_tag("a", text=text, href=target_url, **item["attrs"]) def make_html_tag(tag, text=None, **params): """Create an HTML tag string. tag The HTML tag to use (e.g. 'a', 'span' or 'div') text The text to enclose between opening and closing tag. If no text is specified then only the opening tag is returned. Example:: make_html_tag('a', text="Hello", href="/another/page") -> Hello To use reserved Python keywords like "class" as a parameter prepend it with an underscore. Instead of "class='green'" use "_class='green'". Warning: Quotes and apostrophes are not escaped.""" params_string = "" # Parameters are passed. Turn the dict into a string like "a=1 b=2 c=3" string. for key, value in sorted(params.items()): # Strip off a leading underscore from the attribute's key to allow attributes like '_class' # to be used as a CSS class specification instead of the reserved Python keyword 'class'. key = key.lstrip("_") params_string += u' {0}="{1}"'.format(key, value) # Create the tag string tag_string = u"<{0}{1}>".format(tag, params_string) # Add text and closing tag if required. if text: tag_string += u"{0}".format(text, tag) return tag_string Pylons-paginate-b02abe4/paginate/ext_reverse.py000066400000000000000000000006351466263613500217620ustar00rootroot00000000000000"""Test class to just return reverse elements in a range""" import paginate class ReversePage(paginate.Page): # def __init__(self, *args, **kwargs): # super(ReversePage, self).__init__(*args, **kwargs) def __getitem__(self, key): # if isinstance(key, slice): # return list(reversed(self.collection))[key] # else: return list(reversed(self.collection))[key] Pylons-paginate-b02abe4/setup.cfg000066400000000000000000000002071466263613500171010ustar00rootroot00000000000000[metadata] license_file = LICENSE [bdist_wheel] universal=1 [tool:pytest] addopts = --verbose testpaths = tests python_files = *.py Pylons-paginate-b02abe4/setup.py000066400000000000000000000024641466263613500170010ustar00rootroot00000000000000import os from setuptools import setup, find_packages here = os.path.abspath(os.path.dirname(__file__)) with open(os.path.join(here, 'README.md')) as f: README = f.read() with open(os.path.join(here, 'CHANGELOG.txt')) as f: CHANGES = f.read() setup( name='paginate', version='0.5.7', description="Divides large result sets into pages for easier browsing", long_description=README + '\n\n' + CHANGES, long_description_content_type="text/markdown", # Get strings from http://pypi.python.org/pypi?%3Aaction=list_classifiers classifiers=[ 'Programming Language :: Python', 'Development Status :: 4 - Beta', 'Intended Audience :: Developers', 'License :: OSI Approved :: MIT License', 'Topic :: Software Development :: Libraries :: Python Modules', 'Framework :: Pyramid', 'Framework :: Flask', 'Framework :: Pylons', 'Framework :: Django', ], keywords='pagination paginate pages', author='Christoph Haas', author_email='email@christoph-haas.de', url='https://github.com/Signum/paginate', license='MIT', packages=find_packages(), extras_require={ "dev": ["pytest", "tox"], "lint": ["black"], }, include_package_data=True, zip_safe=False, entry_points=""" """, ) Pylons-paginate-b02abe4/tests/000077500000000000000000000000001466263613500164235ustar00rootroot00000000000000Pylons-paginate-b02abe4/tests/test_paginate.py000066400000000000000000000354371466263613500216400ustar00rootroot00000000000000# -*- coding: utf-8 -*- # Copyright (c) 2007-2012 Christoph Haas # See the file LICENSE for copying permission. """"Test paginate module.""" import pytest import paginate def test_wrong_collection(): """Test whether an empty list is handled correctly.""" with pytest.raises(TypeError): page = paginate.Page({}, page=0) def test_empty_list(): """Test whether an empty list is handled correctly.""" items = [] page = paginate.Page(items, page=0) assert page.page == 1 assert page.first_item is None assert page.last_item is None assert page.first_page is None assert page.last_page is None assert page.previous_page is None assert page.next_page is None assert page.items_per_page == 20 assert page.item_count == 0 assert page.page_count == 0 assert page.pager(url="http://example.org/page=$page") == '' assert page.pager(url="http://example.org/page=$page", show_if_single_page=True) == '' def test_one_page(): """Test that fits 10 items on a single 10-item page.""" items = range(10) page = paginate.Page(items, page=0, items_per_page=10) url = "http://example.org/foo/page=$page" assert page.page == 1 assert page.first_item == 1 assert page.last_item == 10 assert page.first_page == 1 assert page.last_page == 1 assert page.previous_page is None assert page.next_page is None assert page.items_per_page == 10 assert page.item_count == 10 assert page.page_count == 1 assert page.pager(url=url) == '' assert page.pager(url=url, show_if_single_page=True) == '1' def test_many_pages(): """Test that fits 100 items on seven pages consisting of 15 items.""" items = range(100) page = paginate.Page(items, page=0, items_per_page=15) url = "http://example.org/foo/page=$page" assert hasattr(page.collection_type, '__iter__') is True assert page.page == 1 assert page.first_item == 1 assert page.last_item == 15 assert page.first_page == 1 assert page.last_page == 7 assert page.previous_page is None assert page.next_page == 2 assert page.items_per_page == 15 assert page.item_count == 100 assert page.page_count == 7 assert page.pager( url=url) == '1 2 3 .. 7' assert page.pager(url=url, separator='_') == '1_2_3_.._7' assert page.pager(url=url, link_attr={'style': 'linkstyle'}, curpage_attr={'style': 'curpagestyle'}, dotdot_attr={ 'style': 'dotdotstyle'}) == '1 2 3 .. 7' def test_slice_page_0(): items = list(range(1, 1000)) page = paginate.Page(items, page=0, items_per_page=10) assert page.page == 1 assert page.first_item == 1 assert page.last_item == 10 assert page.first_page == 1 assert page.last_page == 100 assert page.previous_page is None assert page.next_page == 2 assert page.items_per_page == 10 assert page.item_count == 999 assert page.page_count == 100 assert page.items == [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] def test_slice_page_5(): items = list(range(1, 1000)) page = paginate.Page(items, page=5, items_per_page=10) assert page.page == 5 assert page.first_item == 41 assert page.last_item == 50 assert page.first_page == 1 assert page.last_page == 100 assert page.previous_page is 4 assert page.next_page == 6 assert page.items_per_page == 10 assert page.item_count == 999 assert page.page_count == 100 assert page.items == [41, 42, 43, 44, 45, 46, 47, 48, 49, 50] def test_link_map(): """Test that fits 10 items on a single 10-item page.""" items = range(109) page = paginate.Page(items, page=0, items_per_page=15) url = "http://example.org/foo/page=$page" format = '$link_first $link_previous ~4~ $link_next $link_last (Page $page our of $page_count - total items $item_count)' result = page.link_map(format, url=url) fpage_result = {'current_page': {'attrs': {}, 'type': 'current_page', 'href': 'http://example.org/foo/page=1', 'value': 1}, 'first_page': {'attrs': {}, 'href': 'http://example.org/foo/page=1', 'number': 1, 'type': 'first_page', 'value': '<<'}, 'last_page': {'attrs': {}, 'href': 'http://example.org/foo/page=8', 'number': 8, 'type': 'last_page', 'value': '>>'}, 'next_page': {'attrs': {}, 'href': 'http://example.org/foo/page=2', 'number': 2, 'type': 'next_page', 'value': '>'}, 'previous_page': {'attrs': {}, 'href': 'http://example.org/foo/page=1', 'number': 1, 'type': 'previous_page', 'value': '<'}, 'range_pages': [{'attrs': {}, 'href': 'http://example.org/foo/page=1', 'number': 1, 'type': 'current_page', 'value': '1'}, {'attrs': {}, 'href': 'http://example.org/foo/page=2', 'number': 2, 'type': 'page', 'value': '2'}, {'attrs': {}, 'href': 'http://example.org/foo/page=3', 'number': 3, 'type': 'page', 'value': '3'}, {'attrs': {}, 'href': 'http://example.org/foo/page=4', 'number': 4, 'type': 'page', 'value': '4'}, {'attrs': {}, 'href': 'http://example.org/foo/page=5', 'number': 5, 'type': 'page', 'value': '5'}, {'attrs': {}, 'href': '', 'number': None, 'type': 'span', 'value': '..'}], 'radius': 4} assert result == fpage_result page = paginate.Page(items, page=100, items_per_page=15) result = page.link_map(format, url=url) l_page_result = {'current_page': {'attrs': {}, 'type': 'current_page', 'href': 'http://example.org/foo/page=8', 'value': 8}, 'first_page': {'attrs': {}, 'href': 'http://example.org/foo/page=1', 'number': 1, 'type': 'first_page', 'value': '<<'}, 'last_page': {'attrs': {}, 'href': 'http://example.org/foo/page=8', 'number': 8, 'type': 'last_page', 'value': '>>'}, 'next_page': {'attrs': {}, 'href': 'http://example.org/foo/page=8', 'number': 8, 'type': 'next_page', 'value': '>'}, 'previous_page': {'attrs': {}, 'href': 'http://example.org/foo/page=7', 'number': 7, 'type': 'previous_page', 'value': '<'}, 'range_pages': [{'attrs': {}, 'href': '', 'number': None, 'type': 'span', 'value': '..'}, {'attrs': {}, 'href': 'http://example.org/foo/page=4', 'number': 4, 'type': 'page', 'value': '4'}, {'attrs': {}, 'href': 'http://example.org/foo/page=5', 'number': 5, 'type': 'page', 'value': '5'}, {'attrs': {}, 'href': 'http://example.org/foo/page=6', 'number': 6, 'type': 'page', 'value': '6'}, {'attrs': {}, 'href': 'http://example.org/foo/page=7', 'number': 7, 'type': 'page', 'value': '7'}, {'attrs': {}, 'href': 'http://example.org/foo/page=8', 'number': 8, 'type': 'current_page', 'value': '8'}], 'radius': 4} assert result == l_page_result page = paginate.Page(items, page=100, items_per_page=15) result = page.link_map(format, url=url, symbol_next=u'nëxt', symbol_previous=u'prëvious') next_page = {'attrs': {}, 'href': u'http://example.org/foo/page=8', 'number': 8, 'type': 'next_page', 'value': u'nëxt'} assert next_page == result['next_page'] def test_empty_link_map(): """Test that fits 10 items on a single 10-item page.""" items = [] page = paginate.Page(items, page=0, items_per_page=15) url = "http://example.org/foo/page=$page" format = '$link_first $link_previous ~4~ $link_next $link_last (Page $page our of $page_count - total items $item_count)' result = page.link_map(format, url=url) assert result == {'current_page': None, 'first_page': None, 'last_page': None, 'next_page': None, 'previous_page': None, 'radius': 4, 'range_pages': []} def test_make_html_tag(): """Test the make_html_tag() function""" assert paginate.make_html_tag('div') == '
' assert paginate.make_html_tag('a', href="/another/page") == '' assert paginate.make_html_tag('a', href="/another/page", text="foo") == 'foo' assert paginate.make_html_tag('a', href=u"/другой/страница", text="foo") == u'foo' assert paginate.make_html_tag('a', href="/another/page", text="foo", onclick="$('#mydiv').focus();") == """foo""" assert paginate.make_html_tag('span', style='green') == '' assert paginate.make_html_tag('div', _class='red', id='maindiv') == '
' def test_url_assertion(): page = paginate.Page(range(100), page=0, items_per_page=10) url = "http://example.org/" with pytest.raises(Exception): page.pager(url=url) def test_url_generation(): def url_maker(page_number): return str('x%s' % page_number) page = paginate.Page(range(100), page=1, url_maker=url_maker) assert page.pager() == '1 2 3 .. 5' def test_pager_without_any_pattern(): def url_maker(page_number): return str('x%s' % page_number) page = paginate.Page(range(100), page=1, url_maker=url_maker) assert page.pager('') == '' def test_pager_without_radius_pattern(): def url_maker(page_number): return str('x%s' % page_number) page = paginate.Page(range(100), page=2, url_maker=url_maker) assert page.pager( '$link_first FOO $link_last') == '<< FOO >>' class UnsliceableSequence(object): def __init__(self, seq): self.l = seq def __iter__(self): for i in self.l: yield i def __len__(self): return len(self.l) class UnsliceableSequence2(UnsliceableSequence): def __getitem__(self, key): raise TypeError("unhashable type") class TestCollectionTypes(object): rng = list(range(10)) # A list in both Python 2 and 3. def test_list(self): paginate.Page(self.rng) def test_list_of_dicts(self): rng = [{'a':x} for x in range(200)] page = paginate.Page(rng) assert page.item_count == 200 def test_tuple(self): paginate.Page(tuple(self.rng)) def test_unsliceable_sequence(self): with pytest.raises(TypeError): paginate.Page(UnsliceableSequence(self.rng)) def test_unsliceable_sequence2(self): with pytest.raises(TypeError): paginate.Page(UnsliceableSequence2(self.rng)) def test_unsliceable_sequence3(self): with pytest.raises(TypeError): paginate.Page(dict(one=1)) Pylons-paginate-b02abe4/tox.ini000066400000000000000000000002771466263613500166020ustar00rootroot00000000000000[tox] envlist = py27,py34,py35,py36,lint [testenv] extras = dev commands= pytest [testenv:lint] basepython = python3.6 extras = dev, lint commands = black --check --verbose paginate