Rants about Java and other internet technologies by Sam Pullara

Idiomatic Python?

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?

"Idiomatic Python?" was published on April 23rd, 2008 and is listed in Technology.

Follow comments via the RSS Feed | Leave a comment | Trackback URL

Comments on "Idiomatic Python?": 1 Comment

  1. leonard wrote,

    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

Leave Your Comment

YUI-Mainstream Theme by Buzzdroid.com

 Premium Wordrpess Theme