Generic AJAX app

This is a Python snippet, talking about django, ajax and dispatcher

Generic AJAX app Add to Favorite

# contrib\ajax\__init__.py
from django.contrib.ajax.dispatcher import dispatcher


# contrib\ajax\dispatcher.py
from django import http
import re

class AlreadyRegistered(Exception):
    pass

class NotCallable(Exception):
    pass

class Dispatcher(object):

    def __init__(self):
        self._funcs = {} # Reference name -> Ajax Function

    def register(self, name, func, force_override=False):
        if not callable(func):
            raise NotCallable('The supplied AJAX function %s is not a function (it is not callable).' % func.__name__)

        if name in self._funcs and not force_override:
            raise AlreadyRegistered('The AJAX function name %s is already registered' % name)

        # Instantiate the admin class to save in the registry
        self._funcs[name] = func

    def has_permission(self, request):
        """
        Returns True if the given HttpRequest has permission to view
        *at least one* page in the admin site.
        """
        return request.user.is_authenticated() and request.user.is_staff

    def urls(self, request, url):
        """
        Handles main URL routing for the admin app.

        `url` is the remainder of the URL -- e.g. 'comments/comment/'.
        """
        if request.method == 'GET' and not request.path.endswith('/'):
            return http.HttpResponseRedirect(request.path + '/')

        # Figure out the admin base URL path and stash it for later use
        self.root_path = re.sub(re.escape(url) + '$', '', request.path)

        url = url.rstrip('/') # Trim trailing slash, if it exists.

        # Check permission to continue or display login form.
        if not self.has_permission(request):
            return http.HttpResponseForbidden('You do not have permission to view the requested information.')

        if url == '':
            return http.HttpResponseForbidden('An AJAX function must be specified.')
        else:
            return self._funcs[url](request)

        raise http.Http404('The requested admin page does not exist.')

dispatcher = Dispatcher()

This is based on the Admin app functionality for dispatching calls. Once you put these two files in place then add the following to urls.py:

from django.contrib import ajax

urlpatterns = patterns('', ... # Add this to the urlpatterns list (r'^ajax/(.*)', ajax.dispatcher.urls), ...) you register a function or method with a name like so:

from django.contrib import ajax

def myAutoCompleteCall(request): ...

ajax.dispatcher.register('myAutoComplete', myAutoCompleteCall) Then you can use the url: http://www.mysite.com/ajax/myAutoComplete

You could place this app in the djangocontrib directory if you wanted to use it in an Admin app mod

Created by prof.syd.xu (395 days, 12.64 hours ago)

Do you want to leave a message? Please login first.