小编sed*_*rep的帖子

Python | 如何从AWS响应的结果中解析JSON?

我正试图获得的价值VersionLabelphp-v1,但我的代码不能正常工作,我不知道我做错了什么.

你能不能让我知道什么是错的,我怎么解析php-v1

这是我的错误消息.

TypeError: the JSON object must be str, not 'dict'

这是我的代码.

#!/usr/bin/env python3

import boto3
import json

def get_label():
   try:
      env_name = 'my-env'
      eb = boto3.client('elasticbeanstalk')
      response = eb.describe_instances_health(
         EnvironmentName=env_name,
         AttributeNames=[
            'Deployment'
         ]
      )
      #print(response)
      data = json.loads(response)
      print(data['VersionLabel'])
   except:
      raise

if __name__ == '__main__':
   get_label()
Run Code Online (Sandbox Code Playgroud)

这是我在print(response)调用AWS时得到的响应.

{
   'InstanceHealthList':[  
      {  
         'InstanceId':'i-12345678',
         'Deployment':{  
            'DeploymentId':2,
            'DeploymentTime':datetime.datetime(2016,
            9,
            29,
            4,
            29,
            26,
            tzinfo=tzutc()),
            'Status':'Deployed',
            'VersionLabel':'php-v1'
         }
      }
   ],
   'ResponseMetadata':{  
      'HTTPStatusCode':200,
      'RequestId':'12345678-1234-1234-1234-123456789012',
      'RetryAttempts':0,
      'HTTPHeaders':{ …
Run Code Online (Sandbox Code Playgroud)

python json boto amazon-web-services

4
推荐指数
2
解决办法
1万
查看次数

AWS Python SDK | 路线53 - 删除资源记录

如何删除Route 53中的DNS记录?我按照文档,但我仍然无法使其工作.我不知道我在这里遗失了什么.

根据文档:

DELETE:删除具有Name,Type,SetIdentifier(用于延迟,加权,地理位置和故障转移资源记录集)和TTL(别名资源记录集除外)的现有资源记录集,其中TTL由您要将DNS查询路由到的AWS资源.

但我总是得到这个错误:

Traceback (most recent call last):                                                                                                                                      
  File "./test.py", line 37, in <module>                                                                                                                                
    main()                                                                                                                                                              
  File "./test.py", line 34, in main                                                                                                                                    
    print(del_record())                                                                                                                                                 
  File "./test.py", line 23, in del_record                                                                                                                              
    'TTL': 300                                                                                                                                                          
  File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/site-packages/botocore/client.py", line 251, in _api_call                                       
    return self._make_api_call(operation_name, kwargs)                                                                                                                  
  File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/site-packages/botocore/client.py", line 537, in _make_api_call                                  
    raise ClientError(parsed_response, operation_name)                                                                                                                  
botocore.exceptions.ClientError: An error occurred (InvalidInput) when calling the ChangeResourceRecordSets operation: Invalid request 
Run Code Online (Sandbox Code Playgroud)

这是我的代码:

#!/usr/bin/env python3


import boto3

r53 = boto3.client('route53')
zone_id = 'ABCDEFGHIJKLMNO'
record = 'me.domain.com'
r_type = …
Run Code Online (Sandbox Code Playgroud)

python dns amazon-web-services amazon-route53 aws-sdk

4
推荐指数
1
解决办法
2758
查看次数

Asyncio 不异步执行任务

我正在使用asyncioPython 模块,但我不知道我的简单代码有什么问题。它不会异步执行任务。

#!/usr/bin/env python3    

import asyncio
import string    


async def print_num():
    for x in range(0, 10):
        print('Number: {}'.format(x))
        await asyncio.sleep(1)    

    print('print_num is finished!')    

async def print_alp():
    my_list = string.ascii_uppercase    

    for x in my_list:
        print('Letter: {}'.format(x))
        await asyncio.sleep(1)    

    print('print_alp is finished!')    


async def msg(my_msg):
    print(my_msg)
    await asyncio.sleep(1)    


async def main():
    await msg('Hello World!')
    await print_alp()
    await msg('Hello Again!')
    await print_num()    


if __name__ == '__main__':
    loop = asyncio.get_event_loop()
    loop.run_until_complete(main())
    loop.close()
Run Code Online (Sandbox Code Playgroud)

这是调用脚本时的输出:

Hello World!
Letter: A
Letter: B
Letter: C
Letter: …
Run Code Online (Sandbox Code Playgroud)

python synchronization asynchronous python-asyncio

3
推荐指数
1
解决办法
3363
查看次数

在尝试访问字典中的键时始终获取KeyError

我正在使用AWS的Boto3编写一个Python脚本来管理安全组.我创建了一个字典来获取组ID及其属性.我可以访问属性,sg-aaaaaaaa但当我试图访问时sg-bbbbbbbb,它总是抛出一个KeyError.

我是如何创建字典的

def get_rules(sg_ids, region):
    sg_rules = {}
    sg_rules['SecurityGroups'] = []
    ec2 = boto3.client('ec2', region_name=region)

    for sg_id in sg_ids:
        response = ec2.describe_security_groups(
            Filters=[
                {
                    'Name': 'group-id',
                    'Values': [
                        sg_id
                    ]
                }
            ]
        )
        data = response['SecurityGroups'][0]['IpPermissions']

        sg_rules['SecurityGroups'].append({sg_id: data})

    return sg_rules
Run Code Online (Sandbox Code Playgroud)

字典

{'SecurityGroups': [{'sg-aaaaaaaa': [{'FromPort': 22, 'IpProtocol': 'tcp', 'IpRanges': [{'CidrIp': 'XX.XX.XX.XX/32'}], 'Ipv6Ranges': [], 'PrefixListIds': [], 'ToPort': 22, 'U
serIdGroupPairs': []}, {'FromPort': 6556, 'IpProtocol': 'tcp', 'IpRanges': [{'CidrIp': 'XX.XX.XX.XX/32'}], 'Ipv6Ranges': [], 'PrefixListIds': [], 'ToPort': 6556, 'UserIdGroup
Pairs': …
Run Code Online (Sandbox Code Playgroud)

python dictionary aws-sdk boto3

0
推荐指数
1
解决办法
1315
查看次数