我正在围绕 boto3 编写自己的包装器,以实现快速触发功能。
我正在尝试输入注释内容boto3.session().client('ec2')
返回。
调试器说是<class 'botocore.client.EC2'>
,但是如果我这样写下来,python就会因运行时错误而崩溃
ec2: botocore.client.EC2
AttributeError: module 'botocore.client' has no attribute 'EC2'
删除类型注释适用于运行时,但它使 linting 非常有限。
有没有一种相当快速的方法或技巧来使用这个 boto3 案例进行打字?
我正在谈论的代码如下:
class AWS_Client:
# debugger says it's <class 'botocore.client.EC2'>,
# but mypy says this class does not exist
ec2: botocore.client.EC2
asg: botocore.client.AutoScaling
region: str
instance_id: str
def __init__(self,
profile_name: Optional[str] = None,
instance_id: str = '',
region_name: str = '',
**kwargs) -> None:
global config
self.instance_id = instance_id or ec2_meta('instance-id').text
self.region = region_name or ec2_meta(
'placement/availability-zone').text[:-1]
boto3.set_stream_logger('botocore', level=logging.DEBUG)
self.session = call_partial(
boto3.Session,
region_name=self.region,
profile_name=profile_name,
**kwargs)
self.ec2 = self.session.client('ec2', region_name=self.region, **kwargs)
self.asg = self.session.client(
'autoscaling', region_name=self.region, **kwargs)
def get_tags(self) -> Dict[str, str]:
self.tags = self.ec2.describe_tags(Filters=[{
'Name': 'resource-id',
'Values': [self.instance_id]
}])['Tags']
return self.tags
aws = AWS_Client()
print(aws.get_tags())