python - 如何使用 Shopify Python API 包装器对结果进行分页

标签 python api shopify

我想使用 Python 包装器分页浏览来自 Shopify API 的结果。 API 最近 (2019-07) 切换到“基于光标的分页”,所以我不能只传递一个“页面”查询参数来获取下一组结果。

Shopify API 文档有一个 page dedicated to cursor-based pagination .

API 响应应该在响应 header 中包含一个链接,其中包含用于发出另一个请求的信息,但我不知道如何访问它。据我所知,包装器的响应是一个没有 header 的标准 Python 列表。

我想我可以在不使用 python API 包装器的情况下完成这项工作,但必须有一种简单的方法来获得下一组结果。

import shopify

shopify.ShopifyResource.set_site("https://example-store.myshopify.com/admin/api/2019-07")
shopify.ShopifyResource.set_user(API_KEY)
shopify.ShopifyResource.set_password(PASSWORD)

products = shopify.Product.find(limit=5)

# This works fine
for product in products:
    print(product.title)

# None of these work for accessing the headers referenced in the docs
print(products.headers)
print(products.link)
print(products['headers'])
print(products['link'])

# This throws an error saying that "page" is not an acceptable parameter
products = shopify.Product.find(limit=5, page=2)

谁能提供一个示例,说明如何使用包装器获取下一页结果?

最佳答案

@babis21 所述,这是 shopify python api 包装器中的错误。该库已于 2020 年 1 月更新以修复它。

对于遇到此问题的任何人,这里有一种简单的方法来翻阅所有结果。同样的格式也适用于产品等其他 API 对象。

orders = shopify.Order.find(since_id=0, status='any', limit=250)
for order in orders:
    # Do something with the order
while orders.has_next_page():
    orders = orders.next_page()
    for order in orders:
        # Do something with the remaining orders

使用 since_id=0 将获取所有订单,因为订单 ID 保证大于 0。

如果你不想重复处理订单对象的代码,你可以像这样把它全部包装在一个迭代器中:

def iter_all_orders(status='any', limit=250):
    orders = shopify.Order.find(since_id=0, status=status, limit=limit)
    for order in orders:
        yield order
    
    while orders.has_next_page():
        orders = orders.next_page()
        for order in orders:
            yield order

for order in iter_all_orders():
    # Do something with each order

如果您正在获取大量订单或其他对象(像我一样用于离线分析),您会发现与其他选项相比,这很慢。 GraphQL API 比 REST API 更快,但是 performing bulk operations with the GraphQL API是迄今为止最有效的。

关于python - 如何使用 Shopify Python API 包装器对结果进行分页,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57504261/

相关文章:

css - 我如何缩小以适合 SHOPIFY 中的横幅图片

shopify - 听shopify购物车更新数量

shopify - 如何测试尚未针对运输 api 发布的新应用程序?

python - 在Python中生成非奇异稀疏矩阵

api - 免费的 LSI 服务或 API 来获取相关关键字

api - RESTful API 认证/安全

java - api中如何定义接口(interface)才合理?抛出异常或者返回ErrorCodeBean结果?

python - 运行容器化的PyTest

python - 使用形状因子级别将 pandas.DataFrame 转换为 numpy 张量

python - 使用python创建新文本文件时出错?