Share
Embed
Patterns for Extensibility
Bringing extensibility to your Django apps enable reuse, will delight your users, and make the world a better place.
Patrick Altman
September 04, 2014
Transcript
23 slides
-
Patterns for Extensibility Patrick Altman VP of Engineering, Eldarion Core
Developer, Pinax @paltman -
Why care about extensibility? • It is the foundation of
reusability • We have a chance to delight our users • We can make the world a better place -
Case 1: Hooksets • django-user-accounts has long sent a number
of emails for various functions • Eldarion’s client needed to control the content of the email templates via a third party solution • We needed the ability to integrate with this third party’s API rather than send the email directly • Creating hooksets in django-user-accounts preserved default behavior while providing a way for us to override the email sending in the site -
Case 1: Hooksets # account/hooks.py class AccountDefaultHookSet(object): # Methods sending
emails the standard way def send_invitation_email(to, ctx): ! class HookProxy(object): def __getattr__(self, attr): return getattr(settings.ACCOUNT_HOOKSET, attr) ! hookset = HookProxy() -
Case 1: Hooksets # account/conf.py class AccountAppConf(AppConf): ! HOOKSET =
"account.hooks.AccountDefaultHookSet" def configure_hookset(self, value): return load_path_attr(value)() # settings.py ACCOUNT_HOOKSET = "your_site.hooks.AccountOverrideHookSet" -
Case 1: Hooksets # account/models.py from account.hooks import hookset !
! class SignupCode(models.Model): def send(self, **kwargs): # building up the context hookset.send_invitation_email([self.email], ctx) # finish things up -
Case 2: Class Based Views • Another Eldarion client had
very specific requirements around password complexity and profile creation at signup. • Out of the box, django-user-accounts has password validation that works great on most sites but didn’t fit this client’s requirements. • We were able to easily leverage all that django-user- accounts gives us by customizing the SignupView and ChangePasswordForm objects with very little code. -
Case 2: Class Based Views # views.py from account.views import
SignupView as AccountSignupView from .forms import SignupForm ! class SignupView(AccountSignupView): form_class = SignupForm def generate_username(self, form): # custom username def create_user(self, form, commit=True, **kwargs): # create the user with first_name / last_name from form def after_signup(self, form): # Create profile and process any coupon codes -
Case 2: Class Based Views # forms.py from account.forms import
( SignupForm as AccountSignupForm ChangePasswordForm as AccountChangePasswordForm, PasswordResetTokenForm as AcccountPasswordResetTokenForm ) ! class SecurePasswordMixin(object): def assert_strong_password(self, data): # raise forms.ValidationError if rules are broken ! class ChangePasswordForm(SecurePasswordMixin, AccountChangePasswordForm): ! class PasswordResetTokenForm(SecurePasswordMixin, AcccountPasswordResetTokenForm): ! class SignupForm(SecurePasswordMixin, AccountSignupForm): # Add extra fields for profile -
Case 2: Class Based Views # urls.py ! url( r"^account/password/$",
ChangePasswordView.as_view(form_class=ChangePasswordForm), name="account_password" ), url( r"^account/password/reset/(?P<uidb36>[0-9A-Za-z]+)-(?P<token>.+)/$", PasswordResetTokenView.as_view(form_class=PasswordResetTokenForm), name="account_password_reset_token" ), url( r"^account/signup/$", SignupView.as_view(), name="account_signup" ), url(r"^account/", include("account.urls")), -
Case 3: Plugins • One of Eldarion’s sites that is
still in early development, KPITree, needed a way to easily extend the number of integrations it could have with 3rd party sources of metrics. • We created an app that will be open sourced and accept pull requests for new integration plugins. • This will enable functionality to be added to KPITree with the site only knowing about the Plugin interface and the Plugin author not having to know about any of the KPITree internals. -
Case 3: Plugins # base.py class PluginRegistry(object): ! def __init__(self):
self._registry = {} ! def register(self, plugin): self._registry[plugin.label] = { "plugin": plugin } ! def get(self, label, default=None) def __getitem__(self, label) def choices(self) ! registry = PluginRegistry() del PluginRegistry -
Case 3: Plugins # base.py class Registerable(type): def __new__(cls, clsname,
bases, attrs): newclass = super(Registerable, cls).__new__( cls, clsname, bases, attrs) if newclass.label is not None: registry.register(newclass) return newclass ! class Plugin(object): __metaclass__ = Registerable ! label = None display_name = None ! def inputs(self) def outputs(self) def fetch(self, start, end) -
Case 3: Plugins # uservoice.py from .base import Plugin !
class UservoicePlugin(Plugin): label = "uservoice" ! def inputs(self): def outputs(self): def fetch(self, start, end): -
Case 3: Plugins # models.py class AutoCollection(CollectionBase): provider = models.CharField(max_length=50,
choices=registry.choices()) inputs = JSONField(default=lambda: {}) ! def clean(self): # validate self.inputs against plugin.inputs ! def process(self): # process data that is fetched from the plugin data = self.plugin().fetch(start, end) ! def plugin(self): return registry.get(self.provider)(**self.inputs) -
Case 3: Plugins # startup.py def autoload(submodules): for app in
settings.INSTALLED_APPS: # import each submodule in each app ! def load_submodules(module): # given a module, import all it's submodules ! def run(): autoload(["receivers"]) load_submodules("kpitree.integrations") admin.autodiscover() -
Case 3: Plugins # wsgi.py import os ! os.environ.setdefault("DJANGO_SETTINGS_MODULE", "kpitree.settings")
! import kpitree.startup as startup startup.run() ! from django.core.wsgi import get_wsgi_application application = get_wsgi_application() -
Case 3: Plugins # manage.py ! if __name__ == "__main__":
os.environ.setdefault( "DJANGO_SETTINGS_MODULE", "kpitree.settings" ) from django.core.management import \ execute_from_command_line import kpitree.startup as startup startup.run() execute_from_command_line(sys.argv) -
Idea to Launch, Faster Patrick Altman VP of Engineering, Eldarion
Core Developer, Pinax @paltman