I have a FileAsset class. I have a set of 'filters' with which I determine if a FileAsset should be written to my database. Below is a telescoped version of how the filters work now. My big question is this: Is there a better way? Any advice would be awesome!
(By the way, the Attribute key in the filters allows me to test other attributes of the FileAsset class which I have not demonstrated for simplicity's sake, but the concept is the same.)
import os
from fnmatch import fnmatch
import operator
class FileAsset:
def __init__(self, filename):
self.filename = filename
@property
def is_asset(self):
filters = [
{'Test':'matches','Attribute':'filename','Value':'*'},
{'Test':'ends with','Attribute':'filename','Value':'txt'},
{'Test':'does not end with','Attribute':'filename','Value':'jpg'}]
results = []
try:
results.append(file_filter(self, filters))
except Exception as e:
results.append(True)
return True in results
def __repr__(self):
return '<FileAsset: %s>' % self.filename
def file_filter(file_asset,filters):
results = []
for f in filters:
try:
attribute = operator.attrgetter(f['Attribute'])(file_asset)
try:
result = filter_map(f['Test'])(attribute,f['Value'])
results.append(result)
except Exception as e:
print e
results.append(False)
except AttributeError as e:
print e
results.append(False)
return not False in results
def filter_map(test):
if test == u'is file':
return lambda x, y: os.path.isfile(x)
elif test == u'contains':
return operator.contains
elif test == u'matches':
return lambda x, y: fnmatch(x,y)
elif test == u'does not contain':
return lambda x, y: not y in x
elif test == u'starts with':
return lambda x, y: x.startswith(y)
elif test == u'does not start with':
return lambda x, y: not x.startswith(y)
elif test == u'ends with':
return lambda x, y: x.endswith(y)
elif test == u'does not end with':
return lambda x, y: not x.endswith(y)
# etc etc
fa1 = FileAsset('test.txt')
fa2 = FileAsset('test.jpg')
print '%s goes to db: %s' % (fa1.filename, fa1.is_asset)
print '%s goes to db: %s' % (fa2.filename, fa2.is_asset)