Skip to main content
 首页 » 编程设计

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

2024年11月01日23jpfss

我想使用 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是迄今为止最有效的。