跳转到主要内容

unitycatalog API的官方Python库

项目描述

Unitycatalog Python API库

PyPI version

Unitycatalog Python库提供了从任何Python 3.7+应用程序方便访问Unitycatalog REST API的功能。该库包括所有请求参数和响应字段的类型定义,并提供了由httpx支持的同步和异步客户端。

它是由Stainless生成的。

文档

REST API文档可以在docs.unitycatalog.com找到。该库的完整API可以在api.md中找到。

安装

# install from the production repo
pip install git+ssh://git@github.com/undefined/unitycatalog-python.git

[!NOTE] 一旦此包在PyPI发布,它将成为: pip install --pre unitycatalog

用法

该库的完整API可以在api.md中找到。

from unitycatalog import Unitycatalog

client = Unitycatalog()

catalog_info = client.catalogs.create(
    name="string",
)
print(catalog_info.id)

异步使用

只需导入AsyncUnitycatalog而不是Unitycatalog,并在每个API调用中使用await

import asyncio
from unitycatalog import AsyncUnitycatalog

client = AsyncUnitycatalog()


async def main() -> None:
    catalog_info = await client.catalogs.create(
        name="string",
    )
    print(catalog_info.id)


asyncio.run(main())

同步客户端和异步客户端的功能相同。

使用类型

嵌套请求参数是TypedDicts。响应是Pydantic模型,它还提供了辅助方法,例如

  • 将对象序列化为JSON,model.to_json()
  • 将其转换为字典,model.to_dict()

类型请求和响应在您的编辑器中提供自动完成和文档。如果您希望在VS Code中看到类型错误以帮助更早地捕获错误,请将python.analysis.typeCheckingMode设置为basic

处理错误

当库无法连接到API(例如,由于网络连接问题或超时)时,会引发unitycatalog.APIConnectionError的子类。

当API返回非成功状态码(即4xx或5xx响应)时,会引发unitycatalog.APIStatusError的子类,其中包含status_coderesponse属性。

所有错误都继承自unitycatalog.APIError

import unitycatalog
from unitycatalog import Unitycatalog

client = Unitycatalog()

try:
    client.catalogs.create(
        name="string",
    )
except unitycatalog.APIConnectionError as e:
    print("The server could not be reached")
    print(e.__cause__)  # an underlying Exception, likely raised within httpx.
except unitycatalog.RateLimitError as e:
    print("A 429 status code was received; we should back off a bit.")
except unitycatalog.APIStatusError as e:
    print("Another non-200-range status code was received")
    print(e.status_code)
    print(e.response)

错误代码如下

状态码 错误类型
400 BadRequestError
401 AuthenticationError
403 PermissionDeniedError
404 NotFoundError
422 UnprocessableEntityError
429 RateLimitError
>=500 InternalServerError
N/A APIConnectionError

重试

默认情况下,某些错误会自动重试2次,带有短指数退避。连接错误(例如,由于网络连接问题)、408请求超时、409冲突、429速率限制以及>=500内部错误都会默认重试。

您可以使用max_retries选项配置或禁用重试设置

from unitycatalog import Unitycatalog

# Configure the default for all requests:
client = Unitycatalog(
    # default is 2
    max_retries=0,
)

# Or, configure per-request:
client.with_options(max_retries=5).catalogs.create(
    name="string",
)

超时

默认情况下,请求在1分钟后超时。您可以使用timeout选项配置此设置,该选项接受一个浮点数或一个httpx.Timeout对象

from unitycatalog import Unitycatalog

# Configure the default for all requests:
client = Unitycatalog(
    # 20 seconds (default is 1 minute)
    timeout=20.0,
)

# More granular control:
client = Unitycatalog(
    timeout=httpx.Timeout(60.0, read=5.0, write=10.0, connect=2.0),
)

# Override per-request:
client.with_options(timeout=5.0).catalogs.create(
    name="string",
)

超时时,会抛出APITimeoutError

请注意,默认情况下会重试超时的请求两次。

高级

日志记录

我们使用标准库logging模块。

您可以通过将环境变量UNITYCATALOG_LOG设置为debug来启用日志记录。

$ export UNITYCATALOG_LOG=debug

如何判断None表示null还是缺失

在API响应中,一个字段可能是显式地null,或者完全缺失;在两种情况下,该库中的值都是None。您可以使用.model_fields_set区分这两种情况

if response.my_field is None:
  if 'my_field' not in response.model_fields_set:
    print('Got json like {}, without a "my_field" key present at all.')
  else:
    print('Got json like {"my_field": null}.')

访问原始响应数据(例如,头部信息)

可以通过在任何HTTP方法调用前加上.with_raw_response.来访问“原始”响应对象,例如

from unitycatalog import Unitycatalog

client = Unitycatalog()
response = client.catalogs.with_raw_response.create(
    name="string",
)
print(response.headers.get('X-My-Header'))

catalog = response.parse()  # get the object that `catalogs.create()` would have returned
print(catalog.id)

这些方法返回一个APIResponse对象。

异步客户端返回具有相同结构的AsyncAPIResponse,唯一的区别是提供了可等待的读取响应内容的方法。

.with_streaming_response

上述接口在您发出请求时急切地读取完整的响应体,这可能并不总是您想要的。

要流式传输响应体,请使用.with_streaming_response,这需要一个上下文管理器,并且只在您调用.read().text().json().iter_bytes().iter_text().iter_lines().parse()时读取响应体。在异步客户端中,这些是异步方法。

with client.catalogs.with_streaming_response.create(
    name="string",
) as response:
    print(response.headers.get("X-My-Header"))

    for line in response.iter_lines():
        print(line)

需要一个上下文管理器,以确保可靠地关闭响应。

制作自定义/未记录的请求

此库已类型化,方便访问已记录的API。

如果您需要访问未记录的端点、参数或响应属性,仍然可以使用此库。

未记录的端点

要向未记录的端点发出请求,您可以使用client.getclient.post和其他http动词来发出请求。在发出此请求时,会尊重客户端选项(例如重试)。

import httpx

response = client.post(
    "/foo",
    cast_to=httpx.Response,
    body={"my_param": True},
)

print(response.headers.get("x-foo"))

未记录的请求参数

如果您想显式发送额外的参数,可以使用 extra_queryextra_bodyextra_headers 请求选项来实现。

未记录的响应属性

要访问未记录的响应属性,您可以访问类似 response.unknown_prop 的额外字段。您还可以通过 response.model_extra 将 Pydantic 模型上的所有额外字段作为一个字典获取。

配置 HTTP 客户端

您可以直接覆盖 httpx 客户端 来自定义它以适应您的用例,包括

from unitycatalog import Unitycatalog, DefaultHttpxClient

client = Unitycatalog(
    # Or use the `UNITYCATALOG_BASE_URL` env var
    base_url="http://my.test.server.example.com:8083",
    http_client=DefaultHttpxClient(
        proxies="http://my.test.proxy.example.com",
        transport=httpx.HTTPTransport(local_address="0.0.0.0"),
    ),
)

管理 HTTP 资源

默认情况下,该库会在客户端被垃圾回收时关闭底层的 HTTP 连接。如果您希望,可以使用 .close() 方法手动关闭客户端,或者使用在退出时关闭的上下文管理器。

版本控制

此包通常遵循 SemVer 规范,尽管某些不向后兼容的更改可能作为次要版本发布

  1. 仅影响静态类型、而不破坏运行时行为的更改。
  2. 对库内部进行的更改,这些更改在技术上对公众开放,但未打算或记录供外部使用。(如果您依赖此类内部结构,请通过 GitHub 中的问题让我们知道)
  3. 我们预计不会影响实践中大多数用户的更改。

我们非常重视向后兼容性,并努力确保您可以信赖平滑的升级体验。

我们渴望您的反馈;请就问题、错误或建议在 issue 中提出。

要求

Python 3.7 或更高版本。

项目详情


下载文件

下载您平台上的文件。如果您不确定选择哪个,请了解更多关于 安装软件包 的信息。

源分布

unitycatalog-0.1.1.tar.gz (64.3 kB 查看散列)

上传时间

构建分布

unitycatalog-0.1.1-py3-none-any.whl (97.6 kB 查看散列)

上传时间 Python 3

支持者

AWS AWS 云计算和安全赞助商 Datadog Datadog 监控 Fastly Fastly CDN Google Google 下载分析 Microsoft Microsoft PSF 赞助商 Pingdom Pingdom 监控 Sentry Sentry 错误记录 StatusPage StatusPage 状态页面