AOP in Python API design - Douwe van der MeijΒΆ

Tags: python, django, pygrunn

AOP is Aspect Oriented Programming. It is not often used in Python, you see it more often in for instance Java.

His program does calculations on biogas installations. And the calculation needs to be exposed through a web API (using Django).

He thought: what about aspects? For instance the security aspect? Statistics/logging aspect? The serialization aspect? All several aspects of the API. He showed a bit of sample code where all these aspects were all inside the same single Django view method. Looked like quite a mixed-up mess (as was his intention).

The resulting code is both scattered and tangled. Scattered because one aspect is scattered all over the place in your code. Tangled because different aspects are often interweaved/mixed.

You can use AOP to fix this. Now, how do we implement this in pure Python?. The number one candidate is decorators.

AOP deals with pointcuts, join points and advices. Advices can be pre, post and around (“a wrapper”). You can use three decorators for these three cases. In the end his example looked a bit like this:

@secure
@serialize
@statistics
@dispatch
def api_call(...):
    ...

AOP offers some brilliant concepts for software engineering. Separate your concerns and aspects; avoid tangling and scattering!

In response to a question: no, this is not a framework, these are just regular decorators. But he used the ideas of AOP to design his decorators.

Station Groningen
blog comments powered by Disqus
 
vanrees.org logo

About me

My name is Reinout van Rees and I work a lot with Python (programming language) and Django (website framework). I live in The Netherlands and I'm happily married to Annie van Rees-Kooiman.

Weblog feeds

Most of my website content is in my weblog. You can keep up to date by subscribing to the automatic feeds (for instance with Google reader):