Sunday, September 12, 2010

Porting from an App Engine RequestHandler to a Django View

For whatever reason, I've found myself porting Python App Engine apps over from App Engine's "django-esque" webapp framework to true django 1.0 with,, and the like.

Besides learning about how and work, I had to do some research to figure out how some of the webapp-isms translated to django-isms, so I thought I'd post my findings here in a table comparing the two:

Webapp Django
author = self.request.get('author') 
What you use depends on how specific you want to be about where parameter was passed:
author = request.GET.get('author') 
author = request.POST.get('author')
author = request.REQUEST.get('author')
class MyRequestHandler(RequestHandler):
  def get(self):
    # Do stuff
  def post(self):
    # Do other stuff
def handle_request(request):
  if request.method == 'GET':
    # do stuff
  elif request.method == 'POST':
    # do other stuff
host =
host = request.get_host()
url = self.request.uri
url = request.build_absolute_uri(request.path)
query_string = request.query_string
query_string = request.META['QUERY_STRING']
return HttpResponse(status=500)
from django.http import HttpResponseServerError
return HttpResponseServerError()
from django.http import HttpResponseRedirect
return HttpResponseRedirect('/gallery') 
path = os.path.join(os.path.dirname(__file__), 'index.html')
self.response.out.write(template.render(path, template_values))
from django.shortcuts import render_to_response 
render_to_response('index.html', path)
Or, if for some reason you need the in-between products of that shortcut (like the generated string), you can use the longer version:
from django.template.loader import get_template
from django.template import Context 

t = get_template('index.html') 
html = t.render(Context(template_values))
return HttpResponse(html) 
self.response.headers['Content-Type'] = 'application/atom+xml'
return HttpResponse(xml, mimetype='application/atom+xml')

If you have suggestions for better "transformations", please let me know. I'm fairly new to Django and am happy to learn more about the right way to do things.

No comments: