如何从 Shopify Python API 获取所有产品 ID

How to get all product id from Shopify Python API

我创建了一个私人 shopify 应用程序。其中几乎可以获取所有带产品id的信息。但是我需要一个选项来获取 API 商店中所有产品的产品 ID。我试过下面的选项

shopify.Product.find()

但它只显示前 50 个产品。但是我的商店有超过 2.4k 种产品。

自 2019-07 起更新: 这将不再有效,因为它已被弃用并随后从 Shopify API.

替换详见

下面是原回答


Shopify returns 对资源列表的分页响应。默认每页资源数50,默认页数1。因此,您的请求等同于以下内容:

shopify.Product.find(limit=50, page=1)

Shopify 允许您将每页的限制增加到 250。这是我用来获取所有给定资源的辅助函数:

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

你这样使用它:

products = get_all_resources(shopify.Product)

你甚至可以传入参数。您的问题专门询问产品 ID - 如果您将查询限制为仅 return ID,这将快得多(因为它不必引入任何产品变体):

product_ids = get_all_resources(shopify.Product, fields="id")

请注意,如果您有 2.4k 个产品,这可能需要一些时间!

文档: https://help.shopify.com/api/reference/product

认为这也可能有帮助:

def get_products():
    """
    Returns a list of all products in form of response JSON
    from Shopify API endpoint connected to storefront.

    * Note: Shopify API allows 250 pruducts per call.

    :return:
        product_list (list):    List containing all product response
                                JSONs from Shopify API.
    """

    products = []
    is_remaining = True
    i = 1
    while is_remaining:

        if i == 1:
            params = {
                "limit": 250,
                "page": i
            }

            response = requests.get(
                "{}/products.json".format(SHOPIFY_ENDPOINT),
                params=params
            )

            products.append(response.json()['products'])
            i += 1

        elif len(products[i-2]) % 250 == 0:
            params = {
                "limit": 250,
                "page": i
            }

            response = requests.get(
                "{}/products.json".format(SHOPIFY_ENDPOINT),
                params=params
            )

            products.append(response.json()['products'])
            i += 1

        else:
            is_remaining = False

    products = [products[i][j]
        for i in range(0, len(products))
        for j in range(0, len(products[i]))
    ]

    return products

Shopify 中的分页界面已更改 API,旧的“限制 + 页”分页方式是 removed in api version 2019-07

换句话说:@Julien 接受的答案在此 api 版本及更高版本中无效。

我在此处使用新方法 relative cursor based pagination 重新创建了已接受答案的函数:

def get_all_resources(resource_type, **kwargs):
    resource_count = resource_type.count(**kwargs)
    resources = []
    if resource_count > 0:
        page=resource_type.find(**kwargs)
        resources.extend(page)
        while page.has_next_page():
            page = page.next_page()
            resources.extend(page)
    return resources

Lennart Rolland 回应的延伸。

正如他所说,首选答案不再适用于 api 2019-07 版。

我无法让他的代码示例工作,因为出现错误“列表没有函数 has_next_page()”。

所以我写了一个使用 'Link' header rel='next' 分页的例子。

def get_all_resources(resource):
    page_info = str()
    resources = list()
    while True:
        resources.extend(resource.find(limit=250, page_info=page_info))
        cursor = shopify.ShopifyResource.connection.response.headers.get('Link')
        if 'next' in cursor:
            page_info = cursor.split(';')[-2].strip('<>').split('page_info=')[1]
        else:
            break
    return resources