在键值对中搜索字符串

Search for a string in a key value pair

正在尝试使用键 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 语句进行过滤。任何线索如何实现过滤器? TIA!

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'}

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

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!