我有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
如何在博客中获取所有文章(非重复)?
答案 0 :(得分:0)
你可能已经想到了这一点,但我最好的猜测是你实际上没有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)。