【问题标题】:shopify.Article.find(blog_id=xxx, limit=50, page=zzz) returns duplicate articlesshopify.Article.find(blog_id=xxx, limit=50, page=zzz) 返回重复文章
【发布时间】:2016-05-12 05:10:49
【问题描述】:

我有 221 篇文章。下面的代码返回 221 篇文章但重复,只有 169 篇唯一文章。

existing_articles = []
for i in xrange(1, 6):
    existing_artciles.extend(shopify.Article.find(blog_id=the_blog.id, limit=50, page=i))
len(existing_articles)
# 211
len(set([a.id for a in existing_articles]))
# 169

如何获取博客中的所有文章(非重复)?

【问题讨论】:

    标签: python shopify


    【解决方案1】:

    您可能已经知道这一点,但我最好的猜测是您实际上并没有 5 页的文章。当您指定的页面大于最后一页时,您只需返回最后一页,这会导致文章重复。

    最好的办法是先获取文章的计数,​​然后用它来确定总页数,并在 xrange 函数中使用它。这是一个函数:

    def get_all_articles():
        article_count = shopify.Article.count()
    
        articles = []
        if article_count > 0:
            for page in xrange(1, ((article_count-1) // 50) + 2):
                articles.extend( shopify.Article.find(page=page) )
    
        return articles
    

    您可以更进一步,将其通用化以处理任何可数的 shopify 资源:

    def get_all_of_resource(resource, **kwargs):
        resource_count = resource.count(**kwargs)
    
        resources = []
        if resource_count > 0:
            for page in xrange(1, ((resource_count-1) // 250) + 2):
                arguments = kwargs
                arguments.update({"limit" : 250, "page" : page})
                resources.extend( resource.find(**arguments) )
    
        return resources
    

    你会这样使用它:

    shirts = get_all_of_resource(shopify.Product, product_type="T-Shirt")
    

    如您所见,我还添加了传递其他参数以过滤结果的功能,并且还请求每页的最大项目数 (250)。

    【讨论】:

      猜你喜欢
      • 2011-08-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-09-08
      • 1970-01-01
      • 1970-01-01
      • 2012-11-20
      • 2018-09-05
      相关资源
      最近更新 更多