如何页面数据集 [英] How to page the dataset

查看:141
本文介绍了如何页面数据集的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想启用以前工作的网页分页,并且在更新环境或实现(不确定哪一个))中破坏它。我想分页由GAE
订购的列表由于对象往往有一个自然排序,即时间,数字,单词等,这个代码可以在某个地方可用吗?我试着做一些像Joey G这样的例子,Google列在这里: http:// code。 google.com/appengine/articles/paging.html
我从URL查询中获取名为书签的参数:

  next = None 
bookmark = self.request.get(bookmark)
category = self.request.get('cg')#category参数
如果书签:
bookmark = datetime.strftime(bookmark [: - 7],%Y-%m-%d%H:%M:%S)
else:
bookmark = datetime .strftime(datetime.now(),%Y-%m-%d%H:%M:%S)

如果cg:
articles = Articles.all() .filter(categories =,cg).filter(modified>,timeline).filter(published =,True).filter(modified< =,bookmark) ).fetch(PAGESIZE + 1)

它曾经工作,现在分页被破坏,也许是因为我不完全明白如何处理e修改和日期时间对象。你能帮我吗?我的用例的URL是www.koolbusiness.com/li
谢谢



编辑/更新:这是显示列表页面的当前代码。它只在几个地方使用 IN ,所以据说它可以重写为没有 IN 的工作,困难在于它分支这很多是由于许多组合可能,即搜索或与nocategory类别,类别或没有搜索,也是地理空间,但我不认为我正在尝试一些不可能的只是需要学习更多的python(有lambda编程涉及我只粘贴,不完全掌握),并在处理所有组合时获得更清晰的结构。

  class I18NListPage(FBBaseHandler,I18NHandler):

def get(self,cursor = None,limit = 60,PAGESIZE = 10,twittername = None):
client = OAuthClient('twitter',self)
如果client.get_cookie():
info = client.get('/ account / verify_credentials')
twittername = info ['screen_name']
if(users.is_current_user_admin()):
timeline = datetime.now() - timedelta(days = limit)
else:
timeline = datetime.now() - timedelta(days = limit)
logo =''
如果util.get_host()。endswith('。br'):
cookie_django_language ='pt-br'
logo ='montao'
translation.activate(cookie_django_language)
self.request.COOKIES ['django_language'] = cookie_django_language
dispatch = 'template / montaoli.html'
else:
cookie_django_language = self.request.get('cookie_django_langu如果self.request.get('cookie_django_language','')else self.request.get('hl','')
dispatch ='template / li.html'
如果cookie_django_language:
如果cookie_django_language =='unset':
del self.request.COOKIES ['django_language']
else:
self.request.COOKIES ['django_language' ] = cookie_django_language
self.reset_language()
next =无
bookmark = self.request.get(书签)
如果不是书签:
bookmark = = str(time.time())

category = self.request.get('cg')
q = self.request.get('q')。encode(utf-8 )
w = self.request.get('q')
cg = self.request.get('cg')
t = self.request.get('t')
f = self.request.get('f')

如果cg而不是t而不是q而不是f:#category没有搜索
ads = Ad.all()。filter (category =,cg).filter(modified >,timeline).filter(published =,True).filter(modified =,bookmark).order( - modified)。fetch(PAGESIZE + 1)
elif q和不是t而不是cg而不是f:#search没有类别
ads = Ad.all()。search(self.request.get('q'))。filter(published =,True)
ads = filter(lambda x:x.modified>时间轴,广告)
ads = filter(lambda x:x.modified <= bookmark,ads)
ads = ads [:PAGESIZE + 1]
ads = sorted(ads,key = lambda x:x.modified,reverse = True)
#iterate list保持时间轴上的元素比书签更新
elif q而不是t和cg而不是f:
ads = Ad。 all()。search(q).filter(type =,'s')。filter(category =,cg).filter(modified>,timeline).filter(published =,True ).filter(modified <=,bookmark).order( - modified)。fetch(PAGESIZE + 1)
elif t而不是f:
ads = Ad.all()。 filter(type =,'w')。filter(modified,timeline).filter(published =,True).filter(modified = ).fetch(PAGESIZE + 1)
elif f =='c':
ads = Ad.all()。filter(company_ad =,True).filter(modified> ,时间线).filter(published =,True).filter(modified =,bookmark).order( - modified)。fetch(PAGESIZE + 1)
elif f =='p':
ads = Ad.all()。filter(company_ad =,False).filter(modified>,timeline).filter(published =,True)。过滤器(修改<=,书签).order( - modified)。fetch(PAGESIZE + 1)
else:
如果util.get_host()。find('onta')> ; 1:
ads = Ad.all()。filter(modified>,timeline).filter(published =,True).filter(url IN,['www.montao.com] (PAGESIZE + 1)
else:
ads = Ad.all(修改) ().filter(modified>,timeline).filter(published =,True).filter(modified< =,书签).order( - modified)。fetch(PAGESIZE + 1)
if util.get_host()。find('onta')> 1和f =='c':
ads = Ad.all()。filter(company_ad =,True).filter(modified>,timeline).filter(published =,True ).filter(url IN,['www.montao.com.br','montao'])。filter(modified=,bookmark).order( - modified)。fetch(PAGESIZE + 1)
elif util.get_host()。find('onta')> 1和f =='p':
ads = Ad.all()。filter(company_ad =,False).filter(modified>,timeline).filter(published =,True ).filter(url IN,['www.montao.com.br','montao'])。filter(modified=,bookmark).order( - modified)。fetch(PAGESIZE + 1)


如果self.request.get('lat'):
m = int(self.request.get('r'))if self.request.get ('r')else 804670
logging.info(m)
lat = self.request.get('lat')
lon = self.request.get('lon')if self.request.get('lon')else self.request.get('lng')
ads = Ad.proximity_fetch(Ad.all()。filter(modified>,timeline).filter( published =,True).filter(modified=,书签).order( - modified),db.GeoPt(lat,lon),max_results = PAGESIZE + 1,max_distance = m)
ads = sorted(ads,key = lambda x:x.modified,reverse = True)
如果广告和len(广告)== PAGESIZE + 1:
next = ads [-1] .modified
ads = ads [:PAGES IZE]

template_values = {'twittername':twittername,'request':self.request,'lat':self.request.get('lat'),'lon':self.request。 get('lon'),'q':q,'w':w,'cg':cg,'t':t,'logo':logo,'ads':ads,'next' user'get_current_user(),'bookmark':bookmark,'q':q,'user_url':users.create_logout_url(self.request.uri)if users.get_current_user()else'login',
'cg':category,'admin':users.is_current_user_admin(),}
template_values.update(dict(current_user = self.current_user,facebook_app_id = FACEBOOK_APP_ID))
path = os.path.join os.path.dirname(__ file__),dispatch)
self.response.out.write(template.render(path,template_values))

更新2:我尝试使用paginator import Paginator,InvalidPage,EmptyPage 中的django paginator类在这种情况下,以下代码实际上页数据集:

  articles = Articles.all()
paginator = Paginator(文章,PAGESIZE)
articles = paginator.page(页)

所以我觉得这个解决方案很诱人,因为它非常简单易读,希望你可以发表评论。

解决方案

在将其传递给客户端之前,您可能需要对64位编码进行编码。
我试过[你的网站] [1],但是如果没有服务器端的错误信息,就不可能清楚地回答你的问题。



此外,分页文章提到,使用datetime作为书签直接会导致问题,同时在同一时间段内发布多个文章(在您的情况下,时间段将为一分钟)。您可能需要考虑使用此格式。

  2008-10-26 04:38:00 | aee15ab24b7b3718596e3acce04fba85 

或使用秒表示时间。

  1310427763.47 | aee15ab24b7b3718596e3acce04fba85 




我应该设置到datetime.now(),如果它是第一页被查看?


您可以通过简单地忽略修改后的第一页结果过滤。
例如:

 如果书签:
建议= Suggestion.all()。order( - 当)
.filter('when&= =',书签).fetch(PAGESIZE + 1)
else:
建议= Suggestion.all()。order( - when ).fetch(PAGESIZE + 1)

或使用当前时间作为书签。

  import time 
bookmark = str(time.time())


Hi I want to enable web pagination that used to work and it broke during an update to the environment or my implementation (not sure which). I want to paginate a list ordered by GAE Since objects tend to have a "natural ordering" ie time, numbers, words etc could this code be already available somewhere usable? I tried doing something like the example from Joey G that Google listed here: http://code.google.com/appengine/articles/paging.html My effort that takes the parameter called bookmark from the URL query:

  next = None
  bookmark = self.request.get("bookmark") 
  category = self.request.get('cg')#category parameter
  if bookmark:
    bookmark = datetime.strftime(bookmark[:-7], "%Y-%m-%d %H:%M:%S")  
  else:       
    bookmark = datetime.strftime(datetime.now(), "%Y-%m-%d %H:%M:%S") 

  if cg: 
    articles = Articles.all().filter("category =", cg).filter("modified >", timeline).filter("published =", True).filter("modified <=", bookmark ).order("-modified").fetch(PAGESIZE+1)    

It used to work and now the paging is broken, perhaps because I don't completely understand how to handle the modified and datetime objects. Could you help me on the way? The URL to my use case is www.koolbusiness.com/li Thanks

EDIT/UPDATE: Here's the current code that displays the list page. It only uses IN at a few places so supposedly it could get rewritten to work without IN the difficulty is that it branches so much due the the many combinations possible ie searching with or with nocategory, category with or with no search and also geospatially but I don't think that I'm trying something impossible it's just that a need to learn more python (there is lambda programming involved that I only pasted in and don't fully grasp) and get a clearer structure when all the combinations are handled.

class I18NListPage(FBBaseHandler,I18NHandler):

  def get(self, cursor=None, limit=60, PAGESIZE = 10, twittername = None):
    client = OAuthClient('twitter', self) 
    if client.get_cookie():
      info = client.get('/account/verify_credentials')
      twittername = info['screen_name']
    if (users.is_current_user_admin()):
       timeline = datetime.now () - timedelta (days = limit)   
    else:
        timeline = datetime.now () - timedelta (days = limit)
    logo = ''             
    if util.get_host().endswith('.br'):
      cookie_django_language = 'pt-br'
      logo = 'montao'   
      translation.activate(cookie_django_language)
      self.request.COOKIES['django_language'] = cookie_django_language
      dispatch= 'template/montaoli.html'
    else:
        cookie_django_language = self.request.get('cookie_django_language', '') if self.request.get('cookie_django_language', '') else self.request.get('hl', '')
        dispatch= 'template/li.html'
    if cookie_django_language:
      if cookie_django_language == 'unset':
        del self.request.COOKIES['django_language']
      else:
        self.request.COOKIES['django_language'] = cookie_django_language
      self.reset_language()       
    next = None
    bookmark = self.request.get("bookmark") 
    if not bookmark:
       bookmark = = str(time.time())

    category = self.request.get('cg')
    q = self.request.get('q').encode("utf-8")
    w = self.request.get('q')
    cg = self.request.get('cg')
    t = self.request.get('t') 
    f = self.request.get('f')

    if cg and not t and not q and not f:#category without search
        ads = Ad.all().filter("category =", cg).filter("modified >", timeline).filter("published =", True).filter("modified <=", bookmark ).order("-modified").fetch(PAGESIZE+1)    
    elif q and not t and not cg and not f:#search without category
        ads = Ad.all().search(self.request.get('q')).filter("published =", True)    
        ads = filter(lambda x: x.modified > timeline, ads)
        ads = filter(lambda x: x.modified <= bookmark, ads)
        ads = ads[:PAGESIZE+1]
        ads = sorted(ads, key=lambda x: x.modified, reverse=True)
        #iterate list keeping elements that are on timeline newer than bookmark
    elif q and not t and cg and not f:
        ads = Ad.all().search(q).filter("type =", 's').filter("category =", cg).filter("modified >", timeline).filter("published =", True).filter("modified <=", bookmark ).order("-modified").fetch(PAGESIZE+1)    
    elif t and not f:
        ads = Ad.all().filter("type =", 'w').filter("modified >", timeline).filter("published =", True).filter("modified <=", bookmark ).order("-modified").fetch(PAGESIZE+1)    
    elif f == 'c':
        ads = Ad.all().filter("company_ad =", True).filter("modified >", timeline).filter("published =", True).filter("modified <=", bookmark ).order("-modified").fetch(PAGESIZE+1)
    elif f == 'p':
        ads = Ad.all().filter("company_ad =", False).filter("modified >", timeline).filter("published =", True).filter("modified <=", bookmark ).order("-modified").fetch(PAGESIZE+1)
    else:
        if util.get_host().find('onta') > 1:
            ads = Ad.all().filter("modified >", timeline).filter("published =", True).filter("url IN", ['www.montao.com.br','montao']).filter("modified <=", bookmark ).order("-modified").fetch(PAGESIZE+1)              
        else:
            ads = Ad.all().filter("modified >", timeline).filter("published =", True).filter("modified <=", bookmark ).order("-modified").fetch(PAGESIZE+1)
    if util.get_host().find('onta') > 1 and f == 'c':
        ads = Ad.all().filter("company_ad =", True).filter("modified >", timeline).filter("published =", True).filter("url IN", ['www.montao.com.br','montao']).filter("modified <=", bookmark ).order("-modified").fetch(PAGESIZE+1)
    elif util.get_host().find('onta') > 1 and f == 'p':
        ads = Ad.all().filter("company_ad =", False).filter("modified >", timeline).filter("published =", True).filter("url IN", ['www.montao.com.br','montao']).filter("modified <=", bookmark ).order("-modified").fetch(PAGESIZE+1)  


    if self.request.get('lat'):
        m=int(self.request.get('r')) if self.request.get('r') else 804670
        logging.info(m)
        lat = self.request.get('lat')
        lon = self.request.get('lon') if self.request.get('lon') else self.request.get('lng')
        ads = Ad.proximity_fetch(Ad.all().filter("modified >", timeline).filter("published =", True).filter("modified <=", bookmark ).order("-modified") ,db.GeoPt(lat, lon),max_results=PAGESIZE+1, max_distance=m)
        ads = sorted(ads, key=lambda x: x.modified, reverse=True)
    if ads and len(ads) == PAGESIZE+1:
      next = ads[-1].modified
      ads = ads[:PAGESIZE]     

    template_values = {'twittername':twittername,'request':self.request,'lat':self.request.get('lat'),'lon':self.request.get('lon'),'q':q,'w':w,'cg':cg,'t':t,'logo':logo,'ads':ads, 'next':next, 'user':users.get_current_user(), 'bookmark':bookmark,'q':q, 'user_url': users.create_logout_url(self.request.uri) if users.get_current_user() else 'login',
            'cg':category,'admin':users.is_current_user_admin(),}
    template_values.update(dict(current_user=self.current_user, facebook_app_id=FACEBOOK_APP_ID))
    path = os.path.join(os.path.dirname(__file__), dispatch)
    self.response.out.write(template.render(path, template_values))

UPDATE 2: I tried using the django paginator class from paginator import Paginator, InvalidPage, EmptyPage in this this case the following code actually pages the data set:

        articles = Articles.all()
        paginator = Paginator(articles,PAGESIZE)
        articles = paginator.page(page)

so I find this solution tempting since it's so easy and readable and hope that you can comment onwards.

解决方案

You may need to base64 encoded your bookmark before you pass it to client. I have tried [Your site][1], but it is impossible to answer your question clearly without the server side error message.

Moreover, as the paging article has mentioned, using datetime as bookmark directly will cause issues while there are more than one articles posted in the same time period (in your case, the time period will be one minute). You may want to consider using this format instead.

2008-10-26 04:38:00|aee15ab24b7b3718596e3acce04fba85

or using seconds to represent the time.

1310427763.47|aee15ab24b7b3718596e3acce04fba85

should I set it to datetime.now() if it's the first page that gets viewed?

You can get the first page results by simply ignore the modified filter. For example:

if bookmark:
    suggestions = Suggestion.all().order("-when")
        .filter('when <=', bookmark).fetch(PAGESIZE+1)
else:
    suggestions = Suggestion.all().order("-when").fetch(PAGESIZE+1)

or using the current time as bookmark.

import time
bookmark = str(time.time())

这篇关于如何页面数据集的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆