Nam Ngo's blog

Musings of a Software Developer.

Django Inspired Design Patterns - Part 1: Middleware

Refactoring code is (most of the time) a fun activity until you hit an obstacle or run out of ways to simplify the code. You’ll find yourself looking for new design patterns from books or even digging inside the source code of your favorite open source projects to find some inspiration. Having worked with Django for 3 years, I find its design philosophy and decisions ideal. As a result, I’ve decided to dedicate a blog series to cover this topic: Django inspired design patterns and how you can use them to refactor your code.

Fibonacci With Caching

Here is my attempt to compare the performance of fibonacci with different ways of caching the results. First implementation uses memoization decorator whereas the second one makes use of defaultdict for caching. You can read my previous blog post on caching with defaultdict.

Fibonacci 1
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
import timeit

def memoize(function):
    memo = {}

    def wrapper(*args):
        if args in memo:
            return memo[args]
        else:
            rv = function(*args)
            memo[args] = rv
            return rv

    return wrapper


@memoize
def fib(num):
    if num == 0:
        return 0
    elif num == 1:
        return 1
    else:
        return fib(num - 1) + fib(num - 2)


t = timeit.Timer(stmt="fib(150)", setup="from __main__ import fib")
print t.timeit()

# Approximate Result: 0.482068061829 seconds

Writing Unit Tests for Django Middleware

Sometimes, it is a pain in the ass to write tests for Django apps (even though Django provides some pretty awesome testing tools out of box). One of the scenarios is testing middleware. Let’s take a look at this middleware.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
from .cart import Cart

class CartMiddleware:
    def process_request(self, request):
        '''Load the current cart from the session, or create a new one'''
        cart = request.session.get('cart', None)

        if cart is None:
            cart = Cart()
        else:
            cart = Cart(**cart)

        setattr(request, 'cart', cart)
        return None

Burn Your Fixtures, Use Model Factories

This blog post is inspired by one of the talks in PyCon US 2012 by Carl Meyer named Testing and Django in which he discusssed the guidelines for writing good tests.

After watching the whole talk, I realised what I’ve been doing is all wrong. The fact that tests I write run within minutes shows how terrible my unit-test-fu is. Using fixtures was a really bad idea. Each test case I wrote would load some fixtures to setup necessary dependencies. Sometimes, this creates a problem when the model has been redesigned. The fixtures would have to be edited due to the change of the model otherwise they won’t be installed properly.

Instead of using fixtures, Carl introduced model factories which would create a model instance with default values. Of course, you will have a flexibility to change those default values to suit each of your test because naturally, when you test a behaviour of a class, you definitely need it to be in different conditions.

Django Custom Email Form Field for Email Pie

As you know Django’s forms.EmailField() is capable of validating email addresses but what if you wanted to validate the existence of a particular email address? I’ve found a pretty neat solution for that, it’s called Email Pie. Email Pie is a wonderful little JSON API that gives you a simple way to validate email addresses. We’ll let you know if that email address is legit or not.. You could either use the service hosted on emailpie.com or run your own instance (it’s open source). In this post, I’m going to show you how to write a custom form field that makes use of Email Pie.

Python Class Factory

Today’s post will be on factory design pattern in Python. You can read more about it in Wiki. This design pattern allows you to create objects without specifying the exact class of object that will be created. Let’s say, you want to create an object based on a provided string.

Here are some classes. Both of them are pets. We want to dynamically create a pet from one of those classes based on a string.

Python Caching Using Defaultdict

Today, I’ve learnt about defaultdict container from my colleague, who uses it for caching. defaultdict container is part of collections module which provides high-performance container datatypes. You can find more about it here. Note: New in version 2.5.

Python Strptime Is Not Thread-safe

When using Python to automate your work, threading is one thing you need to know of. I’ve got into a problem with threading when parsing time. To be exact: datetime.datetime.strptime() function was not thread-safe. Luckily, I found a solution on StackOverflow.

Regenerating Google’s ClientLogin AuthToken in Django

If your application makes use of Google API, you will most likely have to deal with AuthToken expiry (unless you use oAuth). As far as I know, AuthToken generated with ClientLogin authorization expires after 2 weeks. Therefore, it’s good to have a solution to auto regenerate it. First of all, create a model that stores the token and the last updated day.

More on Django FormView

I’ve been trying to limit myself to use class based generic views as much as possible. Django’s generic views were developed to take away the monotony of repeating certain patterns again and again. Some generics views are properly documented (like ListView and DetailView), however I wanted to make use of FormView to process my forms. Unfortunately, there were no FormView examples provided. So here it is.