使用boto3读取AWS CodeCommit文件提示仓库不存在如何解决
问题原因
你遇到的报错核心是两个问题:
- 原有boto3初始化逻辑错误,没有正确创建CodeCommit服务的客户端
- boto3客户端没有指定CodeCommit仓库所在的AWS区域,和你CLI使用的区域不匹配,导致找不到对应区域下的仓库
正确使用语法
写法1:使用默认凭证链(推荐,和AWS CLI复用相同的凭证/区域配置,无需硬编码密钥)
import boto3 # 请将region_name替换为你的CodeCommit仓库实际所在的AWS区域,例如cn-north-1、us-east-1 codecommit_client = boto3.client('codecommit', region_name='替换为实际区域') # 调用get_file接口 response = codecommit_client.get_file( repositoryName='FruitLoops', filePath='apples/granny_smith.json' ) # 返回的fileContent为bytes类型,根据文件编码解码即可读取内容 file_content = response['fileContent'].decode('utf-8')
写法2:显式传入凭证(仅测试用,不推荐在生产环境硬编码密钥)
import boto3 # 初始化session传入凭证和区域 session = boto3.Session( aws_access_key_id='你的AccessKey', aws_secret_access_key='你的SecretKey', region_name='替换为实际区域' ) codecommit_client = session.client('codecommit') response = codecommit_client.get_file( repositoryName='FruitLoops', filePath='apples/granny_smith.json' ) file_content = response['fileContent'].decode('utf-8')
补充说明
AWS CLI能正常运行是因为CLI会自动读取你本地AWS配置(~/.aws/config、环境变量等)中对应的区域,而原有boto3代码没有指定区域,使用了默认的其他区域,因此找不到对应仓库。
内容的提问来源于stack exchange,提问作者alvas
相关产品推荐
相关产品推荐

