如何通过Python API向AR Python仓库推送包及相关疑问
向Artifact Registry Python仓库推送包的方法及Python API实现方案
一、推送Python包的常用方法
- 使用
gcloudCLI:你已成功验证此方式,本质是通过gcloud artifacts python upload命令结合twine完成上传,Artifact Registry兼容PyPI的上传流程。 - 直接用
twine上传:配置~/.pypirc文件,将AR仓库地址作为PyPI源,执行twine upload命令完成推送。 - 通过Python API/客户端库上传:借助官方提供的Python客户端实现程序化上传。
二、关于Artifact Registry与存储桶的说明
Artifact Registry底层虽依赖GCS存储桶,但这些桶属于Google管理的内部资源,不会对用户暴露直接访问权限。你尝试直接操作存储桶时出现“桶未找到”是正常现象,官方不支持通过GCS API直接上传包到AR对应的桶,这种操作也会导致包无法被AR正常识别。
三、Python API实现推送的两种方案
1. 官方Artifact Registry Python客户端(推荐)
通过Google官方客户端库调用专用接口上传,步骤如下:
- 安装依赖:
pip install google-cloud-artifact-registry - 示例代码:
注意:需确保环境已配置好Google Cloud认证(如服务账号密钥、Application Default Credentials)。from google.cloud import artifactregistry_v1 from google.cloud.artifactregistry_v1 import types def upload_python_package(project_id, location, repository_id, package_path): client = artifactregistry_v1.ArtifactRegistryClient() parent = client.repository_path(project_id, location, repository_id) # 方式1:直接上传本地文件 request = types.UploadPythonPackageRequest( parent=parent, local_source=types.LocalSource(path=package_path) ) # 方式2:先上传到自己的GCS临时桶,再由AR拉取 # request = types.UploadPythonPackageRequest( # parent=parent, # gcs_source=types.GcsSource(uris=[f"gs://your-temp-bucket/{package_path}"]) # ) operation = client.upload_python_package(request=request) response = operation.result() print(f"包上传成功:{response}")
2. 调用twine的Python API
利用AR兼容PyPI协议的特性,直接在Python中调用twine的上传逻辑:
- 安装依赖:
pip install twine - 示例代码:
其中仓库URL格式为from twine.commands.upload import main as twine_upload def upload_with_twine(package_files, repo_url, username, password): args = [ "--repository-url", repo_url, "--username", username, "--password", password, *package_files ] twine_upload(args) # 调用示例 upload_with_twine( package_files=["dist/your-package-0.1.0.tar.gz"], repo_url="https://LOCATION-python.pkg.dev/PROJECT-ID/REPOSITORY-ID/", username="_json_key", password="你的服务账号JSON密钥内容" )https://{location}-python.pkg.dev/{project-id}/{repository-id}/,若使用临时访问令牌,用户名填oauth2accesstoken,密码为gcloud auth print-access-token获取的令牌。
内容的提问来源于stack exchange,提问作者Markus T
相关产品推荐
相关产品推荐

