ARTICLE DETAIL

资讯详情

深耕郑州网站建设与运营推广的一线实战洞察。

Dataverse Python SDK 快速上手指南:安装、连接、CRUD、批量操作、分页与文件上传实战

Dataverse Python SDK 快速上手指南:安装、连接、CRUD、批量操作、分页与文件上传实战 Dataverse Python SDK 快速上手指南安装、连接、CRUD、批量操作、分页与文件上传实战【免费下载链接】awesome-copilotCommunity-contributed instructions, agents, skills, and configurations to help you make the most of GitHub Copilot.项目地址: https://gitcode.com/GitHub_Trending/aw/awesome-copilot本指南基于 skills/dataverse-python-quickstart/SKILL.md 展开面向需要快速接入微软 Power Platform Dataverse 的 Python 开发者通过pip安装官方预览版 SDK使用 Azure Identity 凭据建立DataverseClient并完整覆盖单记录 CRUD、批量创建与批量更新广播式与 1:1 配对式、带分页的 Retrieve Multiple 查询以及向 File 列上传文件等核心场景。读完本文你将能独立编写一套可直接运行的 Dataverse Python 集成脚本并掌握每个 API 的返回类型、参数含义与底层行为。前置条件与环境准备在编写代码之前请确认满足以下条件源自 instructions/dataverse-python-sdk.instructions.md一个具有读/写权限的 Dataverse 环境如https://myorg.crm.dynamics.comPython 3.10 及以上版本可访问 PyPI 的网络环境用于安装 SDK 与 Azure Identity 依赖。安装命令官方推荐的安装方式pip install PowerPlatform-Dataverse-Client如需在本地交互式开发场景使用浏览器登录需要同时安装azure-identity若后续涉及 DataFrame 工作流可额外安装pandas详见 instructions/dataverse-python-best-practices.instructions.mdpip install azure-identity pip install pandas # 可选安装完成后可通过以下方式验证 SDK 是否就绪from PowerPlatform.Dataverse import __version__ from PowerPlatform.Dataverse.client import DataverseClient print(fSDK Version: {__version__})建立连接DataverseClient 与 InteractiveBrowserCredentialSDK 的核心入口是PowerPlatform.Dataverse.client模块中的DataverseClient。按官方推荐模式本地开发阶段使用InteractiveBrowserCredential它会弹出浏览器窗口完成 Microsoft 账号登录首次调用触发登录、后续调用复用缓存的令牌。标准连接代码源自 SKILL.md 与官方快速入门指令from azure.identity import InteractiveBrowserCredential from PowerPlatform.Dataverse.client import DataverseClient from PowerPlatform.Dataverse.core.config import DataverseConfig cfg DataverseConfig() # 默认 language_code1033 client DataverseClient( base_urlhttps://myorg.crm.dynamics.com, credentialInteractiveBrowserCredential(), configcfg, )其中DataverseConfig来自 PowerPlatform.Dataverse.core.config管理语言、超时与重试等连接行为是一个不可变配置容器language_code: int 1033—— LCID用于本地化标签与消息默认英语美国http_retries: int | None—— 预留的最大重试次数http_backoff: float | None—— 预留的重试退避系数http_timeout: float | None—— 预留的请求超时秒。SDK 底层采用 Azure Identity 令牌认证而非连接字符串。该机制遵循最小权限原则凭据仅作用于授权应用且可在本地开发、云部署与本地环境间无缝切换无需改动代码。除InteractiveBrowserCredential外instructions/dataverse-python-authentication-security.instructions.md 还提供了生产环境常用的凭据选型DefaultAzureCredential()—— 推荐用于多环境应用按「环境变量服务主体 → VS Code 登录 → Azure CLI → Azure PowerShell → 托管身份」的顺序自动探测可用凭据ClientSecretCredential—— 适用于无人值守的定时任务与本地服务凭据必须存放在环境变量或密钥保管库中严禁硬编码ManagedIdentityCredential—— 适用于 Azure 托管资源App Service、Functions、AKS、VM无需管理任何密钥。单记录 CRUD 操作DataverseClient将增删改查统一封装为四个方法返回类型清晰一致源自 instructions/dataverse-python-sdk.instructions.md 与 instructions/dataverse-python-api-reference.instructions.md# Create返回 list[str]新记录 GUID 列表即使单条也返回列表 account_id client.create(account, {name: Acme, Inc., telephone1: 555-0100})[0] # Retrieve单条记录返回 dictOData 结构可 JSON 序列化 account client.get(account, account_id) # Update返回 None client.update(account, account_id, {telephone1: 555-0199}) # Delete默认走异步批量删除 client.delete(account, account_id)方法签名说明完整参考见 instructions/dataverse-python-api-reference.instructions.mdcreate(table_schema_name, records)—— 入参可传单个 dict 或 dict 列表返回 GUID 列表get(table_schema_name, record_idNone, select, filter, orderby, top, expand, page_size)—— 传record_id返回单条否则按 OData 选项返回分页结果update(table_schema_name, ids, changes)——ids为单个 GUID 或列表changes为单个变更 dict 或配对列表delete(table_schema_name, ids, use_bulk_deleteTrue)—— 返回批量删除任务 ID 或 None。批量操作广播式与 1:1 配对式更新SKILL.md 特别强调了两种批量更新模式它们在处理大批量记录时能显著减少往返次数官方称为 broadcast 与 1:1# 批量创建一次调用返回多个 GUID ids client.create(account, [{name: Contoso}, {name: Fabrikam}]) # 广播式broadcast同一组变更应用到多个 ID client.update(account, ids, {telephone1: 555-0200}) # 1:1 配对式每个 ID 对应各自独立的变更 client.update(account, ids, [{telephone1: 555-1200}, {telephone1: 555-1300}]) # 更大规模的批量创建 payloads [{name: Contoso}, {name: Fabrikam}, {name: Northwind}] ids client.create(account, payloads)在 instructions/dataverse-python-api-reference.instructions.md 中这两种模式的语义被进一步明确# 广播式同一条变更应用到多个 ID client.update(account, [id1, id2, id3], {statecode: 1}) # 配对式逐条对应长度必须一致 client.update(account, [id1, id2], [{name: A}, {name: B}])需要提醒的是预览版 SDK 存在一些限制见 instructions/dataverse-python-performance-optimization.instructions.md默认仅对网络错误重试、不支持DeleteMultiple、通用 OData 批处理能力有限。因此在生产代码中建议为批量操作补充错误跟踪与重试逻辑例如在循环中逐条捕获DataverseError并区分成功/失败记录完整实现见 instructions/dataverse-python-error-handling.instructions.md 的bulk_create_with_error_tracking模式。Retrieve Multiple分页查询top 与 page_sizeSDK 的get方法在查询多条记录时返回分页迭代器每次迭代产出一页数据。SKILL.md 给出的示例pages client.get( account, select[accountid, name, createdon], orderby[name asc], top10, page_size3, ) for page in pages: print(len(page), page[:2])参数含义与性能要点select—— 仅返回所需列可减少 30%–50% 的载荷与内存占用orderby—— 为分页提供稳定顺序推荐「主排序 次排序」组合top—— 限制总返回条数page_size—— 控制每页条数配合迭代器逐页消费。查询优化建议源自 instructions/dataverse-python-performance-optimization.instructions.md# 服务端过滤优于客户端过滤 accounts client.get(account, filterstatecode eq 0, top100) # OData 过滤器示例 # filterstatecode eq 0 # filtercontains(name, Acme) # filterstatecode eq 0 and createdon gt 2025-01-01Z # filterstatecode ne 2 # 稳定的分页顺序 accounts client.get( account, orderby[createdon desc, name asc], page_size100, )文件上传到 File 列SKILL.md 提供了文件列上传的两种调用形态# 单请求上传适合小于 128 MB 的文件 client.upload_file(account, record_id, sample_filecolumn, test.pdf) # 分块上传适合大文件支持条件写入 client.upload_file(account, record_id, sample_filecolumn, test.pdf, modechunk, if_none_matchTrue)更完整的用法来自 instructions/dataverse-python-file-operations.instructions.md。upload_file的完整签名见 instructions/dataverse-python-modules.instructions.mdupload_file(table_schema_name, record_id, file_name_attribute, path, mode, mime_type, if_none_match) → None实战中的策略选择from pathlib import Path def upload_file_smart(client, table_name, record_id, column_name, file_path): 根据文件大小自动选择上传策略。 file_path Path(file_path) file_size file_path.stat().st_size max_single_patch 128 * 1024 * 1024 # 128 MB if file_size max_single_patch: chunk_size None # SDK 走单请求 else: chunk_size 4 * 1024 * 1024 # 4 MB 分块 client.upload_file( table_nametable_name, record_idrecord_id, file_column_namecolumn_name, file_pathfile_path, chunk_sizechunk_size, )分块上传失败时建议配合指数退避重试1s、2s、4s…并对HttpError中的status_code 413文件过大与400列或文件格式非法做针对性处理上传大文件超时可通过增大chunk_size如 8 MB缓解。生产化进阶元数据、错误处理与性能SKILL.md 定位是快速生成片段若要落到生产环境可结合仓库中配套的指令与技能文件进行强化表格元数据创建/删除自定义表instructions/dataverse-python-sdk.instructions.md 提供了建表、写数、删表的完整闭环info client.create_table(SampleItem, { code: string, count: int, amount: decimal, when: datetime, active: bool, }) logical info[entity_logical_name] rec_id client.create(logical, {f{logical}name: Sample A})[0] client.delete(logical, rec_id) client.delete_table(SampleItem)选项集列可用IntEnum定义详见 instructions/dataverse-python-api-reference.instructions.md例如class ItemStatus(IntEnum): ACTIVE 1; INACTIVE 2并将其作为列类型传入create_table。结构化错误处理SDK 提供以DataverseError为基类的异常层级ValidationError、MetadataError、HttpError、SQLParseError统一暴露code、subcode、status_code、source、is_transient与details等诊断字段。处理原则见 instructions/dataverse-python-error-handling.instructions.md不要重试401认证、403授权、400客户端错误、404资源不存在考虑重试408、429、500、502、503、504配合指数退避。from PowerPlatform.Dataverse.core.errors import DataverseError import time def create_with_retry(client, table_name, payload, max_retries3): for attempt in range(max_retries): try: return client.create(table_name, payload) except DataverseError as e: if e.status_code 429 and e.is_transient: time.sleep(2 ** attempt) else: raise客户端生命周期与性能建议复用单个DataverseClient实例单例模式见 skills/dataverse-python-production-code/SKILL.md并统一使用select/filter做服务端裁剪、用logger而非print记录审计日志、为所有公开函数补充类型注解与 docstring。常见问题速查问题诊断解决方案401 Unauthorized令牌过期或凭据错误使用有效凭据重新认证403 Forbidden用户缺少权限由管理员分配 Dataverse 安全角色404 Not Found记录/表不存在核对逻辑名与记录 ID429 Rate Limited请求超过服务保护限额实现指数退避重试413 文件过大超过单请求上限改用modechunk分块上传网络超时连接问题检查网络调整DataverseConfig超时参数相关仓库资源技能定义skills/dataverse-python-quickstart/SKILL.md官方快速入门指令instructions/dataverse-python-sdk.instructions.md模块与 API 参考instructions/dataverse-python-modules.instructions.md、instructions/dataverse-python-api-reference.instructions.md认证与安全instructions/dataverse-python-authentication-security.instructions.md错误处理与文件操作instructions/dataverse-python-error-handling.instructions.md、instructions/dataverse-python-file-operations.instructions.md性能优化与最佳实践instructions/dataverse-python-performance-optimization.instructions.md、instructions/dataverse-python-best-practices.instructions.md生产级代码技能skills/dataverse-python-production-code/SKILL.md、skills/dataverse-python-advanced-patterns/SKILL.md【免费下载链接】awesome-copilotCommunity-contributed instructions, agents, skills, and configurations to help you make the most of GitHub Copilot.项目地址: https://gitcode.com/GitHub_Trending/aw/awesome-copilot创作声明:本文部分内容由AI辅助生成(AIGC),仅供参考
返回列表