【问题标题】:Search for a string in a key value pair [duplicate]在键值对中搜索字符串 [重复]
【发布时间】:2021-02-09 05:01:06
【问题描述】:

尝试使用键 i['DBSnapshotIdentifier'] 过滤 RDS 数据库名称。

示例数据库名称:db-test-709-au50-2020-10-17db-test-uk10-2020-10-17

        print('Deleting all DB Snapshots older than %s' % retentionDate)
        
        for i in response['DBSnapshots']:
            print(i['DBSnapshotIdentifier']) # gives: db-test-709-au50-2020-10-17
            if (i['SnapshotCreateTime'] < retentionDate) and (i['DBSnapshotIdentifier'] == "*-au50*" or i['DBSnapshotIdentifier'] == "*-uk10*"):
                print ('Deleting snapshot %s' % i['DBSnapshotIdentifier'])

试图弄清楚如何使用上面的 if 语句进行过滤。任何线索如何实现过滤器?蒂亚!

print(i) 给出:

{u'MasterUsername': 'root', u'LicenseModel': 'postgresql-license', u'InstanceCreateTime': datetime.datetime(2017, 5, 23, 7, 52, 47, 355000, tzinfo=tzlocal()), u'Engine': 'postgres', u'VpcId': 'vpc-64b09', u'DBSnapshotIdentifier': 'db-test-709-au50-2020-10-17', u'AllocatedStorage': 5, u'Status': 'available', u'PercentProgress': 100, u'DBSnapshotArn': 'arn:aws:rds:eu-west-1:754878741835:snapshot:db-test-709-au50-2020-10-17', u'EngineVersion': '9.5.4', u'ProcessorFeatures': [], u'OptionGroupName': 'default:postgres-9-5', u'SnapshotCreateTime': datetime.datetime(2017, 5, 23, 8, 9, 24, 683000, tzinfo=tzlocal()), u'AvailabilityZone': 'eu-west-1a', u'StorageType': 'standard', u'Encrypted': False, u'IAMDatabaseAuthenticationEnabled': False, u'DbiResourceId': 'db-KQBQVZRNHHGHHJKIY3NZONZX5E', u'SnapshotType': 'manual', u'Port': 5432, u'DBInstanceIdentifier': 'db-test-709-au50'}

【问题讨论】:

  • 使用re.search。还要检查regular-expression
  • 我回滚了您最近的编辑,因为它 (a) 将其变成了副本,并且 (b) 使某人刚刚发布的答案无效。
  • 你不需要正则表达式; if "-au50" in i['DBSnapshotIdentifier']

标签: python amazon-rds


【解决方案1】:

您可以在这里尝试这种方法:

import re
import functools 

def identifierFilter(identifier, patterns):
  return functools.reduce(lambda a,b : a or b, 
                          map(lambda pattern: pattern in identifier, patterns))

def snapshotFilter(ele, params):
  return (ele['SnapshotCreateTime'] < params["retentionDate"]) 
         and identifierFilter(ele["DBSnapshotIdentifier"], params["dbIdentifierPattern"])

snapshotParams = {
                   "retentionDate": retentionData, 
                   "dbIdentifierPattern": ["-au50-", "-uk10-"]
                 }

snapshotsToDelete = filter(lambda ele: snapshotFilter(ele, snapshotParams), response['DBSnapshots'])        

print('Deleting all DB Snapshots older than %s' % retentionDate)

for snapshot in snapshotsToDelete:
  print ('Deleting snapshot %s' % snapshot['DBSnapshotIdentifier'])

# Bonus: Write tests for the above!

【讨论】:

猜你喜欢
  • 2013-05-27
  • 2020-03-21
  • 1970-01-01
  • 1970-01-01
  • 2018-02-03
  • 2016-11-15
  • 2016-06-01
  • 2016-09-25
  • 1970-01-01
相关资源
最近更新 更多