Refactor to only sort once

Rather than doing the sort every time an instance is initiated, we can
speed things up by just doing it the once when the app starts up.
This commit is contained in:
Chris Hill-Scott
2018-02-06 14:00:09 +00:00
parent 641511ce12
commit be18448f2a

View File

@@ -445,31 +445,33 @@ class GovernmentDomain:
with open('{}/domains.yml'.format(_dir_path)) as domains: with open('{}/domains.yml'.format(_dir_path)) as domains:
domains = yaml.safe_load(domains) domains = yaml.safe_load(domains)
domain_names = sorted(domains.keys(), key=len)
def __init__(self, email_address_or_domain): def __init__(self, email_address_or_domain):
try: try:
self._match = sorted( self._match = next(filter(
( self.get_matching_function(email_address_or_domain),
domain for domain in self.domains.keys() self.domain_names,
if self._domain_matches(email_address_or_domain, domain) ))
), except StopIteration:
key=len
)[0]
except IndexError:
raise NotGovernmentDomain() raise NotGovernmentDomain()
self.owner, self.sector, self.agreement_signed = self._get_details_of_domain() self.owner, self.sector, self.agreement_signed = self._get_details_of_domain()
@staticmethod @staticmethod
def _domain_matches(email_address_or_domain, domain): def get_matching_function(email_address_or_domain):
email_address_or_domain = email_address_or_domain.lower() email_address_or_domain = email_address_or_domain.lower()
return (email_address_or_domain == domain) or re.search( def fn(domain):
"[\.|@]({})$".format(domain.replace(".", "\.")),
email_address_or_domain return (email_address_or_domain == domain) or re.search(
) "[\.|@]({})$".format(domain.replace(".", "\.")),
email_address_or_domain
)
return fn
def _get_details_of_domain(self): def _get_details_of_domain(self):