REST-like web services in Django

14 views
Skip to first unread message

jay....@gmail.com

unread,
Nov 1, 2006, 5:58:25 PM11/1/06
to Django users
Hi everyone,

Just thought I'd throw out an implementation I've been kicking around
for an app I'm building. Just wanted to get the groups thoughts.

I know this violates MVC in a way, you can do this writing out url
files and views seperately, but some of the flexibility of having
models define services for themselves made sense to me. It's dark in
Knoxville these days and the crack is readily in supply...

in my model, for example:

class Person(models.Model):
first_name = models.CharField(maxlength=150)
last_name = models.CharField(maxlength=150)

def __str__(self):
return "%s, %s" % (self.last_name, self.first_name)

class REST_Service:
method_map = {
'people/$' : 'myproj.myapp.views.get_people',
}

then in my services/urls.py, and this is where I think it gets really
(ugly|awesome):

from django.conf.urls.defaults import *
from django.conf import settings
from django.db import models

pattern_list = []

# add a little safety check so we can't expose django apps
installed_apps = [item.split(".").pop() for item in
settings.INSTALLED_APPS if not item.startswith("django")]

for app in installed_apps:
app_mod = models.get_app(app)
model_list = [model for model in models.get_models(app_mod) if
hasattr(model, "REST_Service")]

for model in model_list:
service_class = model.REST_Service
for key in service_class.method_map.keys():
pattern = (r'%s/%s' % (app, key),
service_class.method_map[key])

pattern_list += pattern

urlpatterns = patterns('', pattern_list)

effectively making your service URL thus: /services/myapp/people/

then you'd define a view called get_people in your views.py:

def get_people(request):
to_return = [str(person) for person in
People.objects.all().order_by('last_name')]

return HttpResponse(str(to_return))

granted the view is ugly, but you could wrap this up in XML from a
template or send it out via the JSON encoder.

But it gives you flexibility to define REST-like grammars with your
django applications fairly dynamically, although you munge a big
portion that MVC seperation gives you.

Any ideas, questions, comments or is this a big ugly something that
needs to go back to the depths which it came?

Reply all
Reply to author
Forward
0 new messages