You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Azure Data Table V12.6.0 Python API分页与continuation token获取问题

Azure Data Table V12.6.0 Python API分页与continuation token获取问题

我之前也碰到过类似的问题,你现在的代码之所以返回所有200条记录,是因为query_entities返回的是TableEntityPaged迭代器对象,直接用for entity in entities遍历它时,会自动拉取所有后续页面的数据,相当于忽略了results_per_page的设置。另外,continuation token就藏在这个迭代器对象的属性里,下面给你调整下代码,实现分页获取和token的保存:

首先,修改你的get_chat_history函数,让它同时返回当前页的聊天记录和对应的continuation token:

def get_chat_history(notebook_id: str, user_id: str, continuation_token=None):
    """
    Get the chat history for a notebook for a user, supports pagination with continuation token.
    """
    table_service_client = connect_table_storage()
    table_name = os.getenv("AZURE_CHAT_HISTORY_TABLE_NAME")
    table_client = table_service_client.get_table_client(table_name=table_name)

    # 调用query_entities时传入continuation_token(首次请求传None)
    entities = table_client.query_entities(
        query_filter=f"NotebookId eq '{notebook_id}' and PartitionKey eq '{user_id}'",
        select=["Role", "Content"],
        results_per_page=10,
        continuation_token=continuation_token
    )
    
    chat_history = []
    # 只取当前页的实体,不要直接遍历整个迭代器(否则会自动拉所有页)
    current_page = list(entities)
    for entity in current_page:
        chat_history.append({
            "Timestamp": entity._metadata["timestamp"],
            "Role": entity["Role"],
            "Content": entity["Content"]
        })
    
    # 获取当前页对应的continuation token,没有更多数据时为None
    next_continuation_token = entities.continuation_token
    
    return chat_history, next_continuation_token

然后你可以这样使用这个函数:

  1. 首次加载聊天记录:
# 第一次调用,不传continuation_token
first_page_history, next_token = get_chat_history("your-notebook-id", "your-user-id")
# first_page_history里是10条记录,next_token用来获取下一页
  1. 用户需要加载更多时,传入上一次拿到的next_token:
# 后续加载,传入之前拿到的continuation token
next_page_history, new_next_token = get_chat_history("your-notebook-id", "your-user-id", continuation_token=next_token)
# 如果new_next_token是None,说明已经没有更多数据了

这里要注意几个关键点:

  • 必须用list(entities)获取当前页的所有实体,不能直接遍历entities,否则迭代器会自动拉取下一页数据直到全部加载完成。
  • entities.continuation_token就是续传令牌,每次请求后都要保存它,下次请求时传入就能拿到下一页的10条记录。
  • 当所有数据加载完毕后,continuation_token会变成None,此时无需再发起请求。

备注:内容来源于stack exchange,提问作者Yasin Amini

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.04.14 16:12:57