java rants

April 23, 2008

Idiomatic Python?

Filed under: Technology — Tags: , , — sam @ 11:19 am

I’ve been working my way through compiling Java into Python code but the Python back end of my isn’t that good (my brain). I would call my stage of Python development the “magic incantation” stage. This is the stage where you really aren’t comfortable yet with the way things work in a new language but you can still get things done by miming other developers. I’ve also had some help from some friends on Twitter: @lhl, @precipice and @jkwatson.  My distributed information system is now getting some redundancy.  Little did they know that I was doing parallel invocations of identical requests for reliability and incrementally higher performance — and the results were verified using a quorum of responders.

Here is my first service that I am porting. It takes an RSS feed (in JSON format from Pipes) and combines all the entries from each day into a single entry:

import logging
import wsgiref.handlers

from datetime import date
from google.appengine.ext import webapp
from django.utils import simplejson

class DayBinPipesWebService (webapp.RequestHandler):
 def post(self):
 	now = date.today()
 	now = now.strftime("%m/%d/%Y")
 	data = self.request.get("data")
 	items = simplejson.loads(data)["items"]
 	bins = {}
 	for item in items:
 		published = item["y:published"]
 		updateDay = “%(month)02d/%(day)02d/%(year)04d” % published
 		if now != updateDay:
 			bin = bins.get(updateDay, [])
 			bin.append(item)
 			bins[updateDay] = bin
 	entries = []
 	for bin in bins.items():
 		dayDate = bin[0]
 		binEntries = bin[1]
 		first = binEntries[0].copy()
 		first["description"] = “”
 		for e in binEntries:
 			first["description"] += “<p><a href=’%(link)s’>%(title)s</a><br>%(description)s</p>” % e
 		first["title"] = “Items from ” + dayDate
 		first["link"] = “”
 		entries.append(first)
 	self.response.content_type = “application/json”
 	simplejson.dump(entries, self.response.out)

How would you write this in idiomatic Python as opposed to my rudimentary translation? Would you change the whole design?

Bookmark on del.icio.us

1 Comment »

    One Response to “Idiomatic Python?”

    1. Avatarleonard
      1

      not gonna have a chance to take a look in the next couple days, but on the topic of idiomatic python, i’m assuming you’ve read: http://python.net/~goodger/projects/pycon/2007/idiomatic/handout.html

      Reply to this comment.

RSS feed for comments on this post. TrackBack URL

Leave a comment

© Sam Pullara -- Powered by WordPress