Pages

Best Way to Implement Paging On AppEngine (Python)

Hi,
I was trying to do pagination on AppEngine, and was trying to find best solution because pagination is not just the matter of solving, that might be easy but question is what is the best way to do it so that performance is also good and you are not overloading the db queries. I evaluated various libraries available online for paging and found that this library is best one

http://code.google.com/p/he3-appengine-lib/wiki/PagedQuery

Read the API Documentation here, its very easy to use. It wraps your db object so you might not have to do too much of refactoring in your existing code.

Here is example of python code using this library
from google.appengine.ext import db
from google.appengine.ext.webapp import RequestHandler, WSGIApplication
import paging;
from paging import *

class SomeStuff(db.Model):
  userHandle= db.StringProperty()
  date = db.DateTimeProperty(auto_now_add=True)
 
def getMyStuff(user,page):
 query = SomeStuff.all()
 query.filter('userHandle =', user);
 query.order("-date")
        #Here i am using the class from library, 
        #download the code from link given above
 myPagedQuery = PagedQuery(query, 10)
 ret={};
 if page>1:
  ret["results"] = myPagedQuery.fetch_page(page);
 else:
  ret["results"] = myPagedQuery.fetch_page();
 ret["nextPageExists"] = myPagedQuery.has_page(page+1);
 if page-1 >0:
  ret["prevPageExists"] = myPagedQuery.has_page(page-1);
 else:
  ret["prevPageExists"]=False;
 return ret;
class UserPage(RequestHandler):
    def get(self):
        screenname=get_current_user();
        page=self.request.get("page", default_value="1");
 page=int(page);
 pageinfo=getMyStuff(screenname,page);
 stuffs=pageinfo["results"];
 next_page=None;
 prev_page=None;
 if pageinfo["nextPageExists"]: next_page=page+1;
 if pageinfo["prevPageExists"]: prev_page=page-1;
 template_values = {
  "screenname":screenname,
  "stuffs":stuffs,
  "next_page":next_page,
  "prev_page":prev_page
            }
 path = os.path.join(os.path.dirname(__file__), 'userpage.html');
 self.response.out.write(template.render(path, template_values));



And here is the page template


<ul>
{%for stuff in stuffs%}
 <li>
  {{stuff.date|timesince}} ago
 </li>
{%endfor%}
</ul>
{% if prev_page %}   
<a href="/page?page={{prev_page}}">Previous Page</a>   
{% endif %}   

{% if next_page %}   
<a href="/page?page={{next_page}}">Next Page</a>   
{% endif %}   

2 comments:

  1. Hi

    Thanks for doing the work of evaluating. Can you tell us more about the evaluation you've done.

    Thanks,
    James

    ReplyDelete
  2. That's great. I 'm already using it.
    Thanks a lot!!!

    ReplyDelete

Your comment will inspire me, Please leave your comment