2016-05-12 18 views
1

我有221篇文章。下面的代碼返回221篇文章,但重複,只有169篇獨特的文章。shopify.Article.find(blog_id = xxx,limit = 50,page = zzz)返回重複文章

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

你可能已經知道了這一點,但我最好的猜測是你實際上沒有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)。