Posts tagged ‘django’

Django is cute

I’ve been playing around a bit more with django, and writing simple web services in it. I have to say it’s cute!

Building on my simple authentication middleware I added a second decorator that extract argument out of the URL and passes them to the function as regular arguments:

def extract_arguments(required, optional):
    def _wrapper(func):
        def _iwrapper(request):
            kwargs = {}
            try:
                for r in required:
                    kwargs[r] = request.GET[r]
            except MultiValueDictKeyError, e:
                return HttpResponse(’Failure’)
            for o in optional:
                if request.GET.get(o, ”):
                    kwargs[o] = request.GET[o]
            return func(request, **kwargs)
        return _iwrapper
    return _wrapper

This allows me to write functions like this

@extract_arguments(['req1', 'req2'], ['opt1', 'opt2'])
def exposed_func(req1, req2, opt1=’default’, opt2=”):
    # perform magic

Yes it’s lacking in type information, but it shouldn’t be too difficult to add that if the need arises. For now string are enough.

I’m also impressed with the documentation. It didn’t take me long to dig out unique_together in the model reference. I have to admit I was stuck at the thought of a generic unique_for field option, luckily I scrolled down and read through the meta options as well.

Django on GoogleVideo

A rather long (more than 1h) video of Jacob Kaplan-Moss’ presentation on Django at Google.

Rolling your own authentication in Django

For various reasons I wanted to see just what was required to roll my own basic authentication using Django. I am aware there’s a built-in authentication module, django.contrib.auth, but it’s overkill for my ultimate goal and it depends on the session module in ways that only further study can reveal. I heard rumours that the authentication module would be pluggable. The only pluggable aspect of it that I found was the backend (i.e. the data model).

In the end the most relevant reason for doing this was that I wanted to :-)

So, what’s involved in it? It turns out, not much!

First I created a middleware class that extracts the authentication credentials (read username and password) and sticks a ‘user object’ in the request depending on just how successfully it does this:

from base64 import b64decode
from models import User, AnonUser, BadUser

class MiniAuthMiddleWare(object):
    def process_request(self, request):
        auth = request.META.get('Authorization', '') or \
                request.META.get('HTTP_AUTHORIZATION', '')
        if not auth:
            request.user = AnonUser()
            return

        name, pwd = b64decode(auth[6:]).split(’:')
        try:
            u = User.objects.get(name=name)
            if pwd != u.passwd:
                request.user = BadUser()
                return
            request.user = u
            return
        except User.DoesNotExist, e:
            request.user = BadUser()
        except AssertionError, e:
            request.user = BadUser()

        return

The model related to this is rather minimal:

from django.db import models

class User(models.Model):
    name = models.CharField(maxlength=50, primary_key=True)
    passwd = models.CharField(maxlength=50)

    def is_authenticated(self):
        return True

class AnonUser:
    name = 'Anonymous'
    passwd = 'NoPass'

    def is_authenticated(self):
        return False

class BadUser:
    name = 'BadUser'
    passwd = 'NoPass'

    def is_authenticated(self):
        return False

Then I decorated the functions/urls that required authentication with the following:

def _RequireAuthorization(func):
    def _wrapper(request):
        if not request.user.is_authenticated():
            response = HttpResponse()
            response.status_code = 401
            response['WWW-Authenticate'] = ‘Basic Realm=”Silly Realm”‘
            return response
        else:
            return func(request)
    return _wrapper

That all seems to work just fine :-)

Django on Debian

Brett Parker’s been packaging django for Debian and making it available to the world. The latest update was just 2 weeks ago. Unfortunately the packages seem to have been made before the very recent move to Python 2.4 in Debian Sid, so they aren’t installable without downgrading :(

Django seems cool

I’ve spent a few hours tonight playing with django. I have a small project in mind and at first I thought I’d just go for cherrypy since I’ve played with that before. After hearing Guido’s praise for django on FLOSS weekly I decided to take a look at it.

At first I was overwhelmed. Then I was confused. Then I was impressed. I’ve decided to play a bit more and it looks like I’ll end up using it.