Search code examples
pythonpython-3.xpython-2.7pyramid

Replacing webhelpers with paginate: how to port PageURL_WebOb? (py2 to py3)


Porting Python 2 to Python 3

As you can read here the Python 2 package webhelpers.paginate no longer exists under Python 3. Instead they created an extra module paginate for Python 3 (which can be found here).

Python 2

When working with pyramid under Python 2, the code looks like this:

# request is a pyramid request
def get_paginator(request, page=1, items_per_page=10):
    page_url = PageURL_WebOb(request)
    return Page(sql-query-here, page, url=page_url, items_per_page=items_per_page)

Python 3

Under Python 3 they removed the PageURL_WebOb from paginate. So is it somehow possible to retrieve the page_url directly from the request?

How would a correct port to Python 3 look like?


Solution

  • So with the help of Steve Piercy and this issue from the official paginate git I was able to port it in the following way:

    # request is a pyramid request
    def get_paginator(request, page=1, items_per_page=10):
        def url_maker(page_number):
            query = request.GET
            query["page"] = str(page_number)
            return request.current_route_url(_query=query)
    
        return Page(sql-query-here, page=page, items_per_page=items_per_page, url_maker=url_maker)