Last Updated: February 25, 2016
·
1.719K
· geeknam

Django Middleware-like design pattern

PIPELINE = (
    'validation.contains_dot',
    'validation.contains_at',
    'mutators.lowercase_domain',
    'mutators.lowercase_name',
    'validation.does_not_bounce_back',
)


class EmailValidator(object):

    def __init__(self, email):

        self._pipelines = []
        self.load_pipelines()
        self.email = email

        for func in self._pipelines:
            res = func(self.email)
            if res:
                self.email = res

    def get_email(self):
        return self.email

    def load_pipelines(self):
        for line in PIPELINE:
            mod_name, func_name = line.split('.')
            mod = __import__(mod_name)
            func = getattr(mod, func_name)
            self._pipelines.append(func)


email = EmailValidator('Test@UPPER.COM').get_email()
print email

2 Responses
Add your response

It seems that you could do something similar with decorators too.

over 1 year ago ·

Yes, decorators can do the same thing. But imagine stacking 10 decorators on top of the function + always having to remember to wrap them? This example allows you to: easily unit test your pipelines since they are broken down into small units + it's easy to plug a new pipeline if you want to extend the feature (manipulate data further).

over 1 year ago ·