3am is when the world is most interesting.
Random header image... Refresh for more!

Category — Tech

Python MySQLdb snippet

So, for the past few weeks, I’ve been hacking around with Python’s MySQLdb DBAPI v2 driver. After getting so used to mysqli in PHP, the move to MySQLdb was a mixed bag – some things are awesome, others not so much.

First the awesome – it’s so much cleaner to do safe, simple queries with python’s dbapi, than with the PHP mysqli stuff. Just call cursor.execute(query, arguments) and pass in your SQL and it’s arguments, and all the escaping and safety stuff is taken care of behind the scenes. No ugly hacks to check to see if something is a digit or a string and to properly escape/format the final query for you. In addition to that, connecting and setting the character set and forcing the driver to use unicode is all just 2 little options passed in the connect() method.

Now, the not so awesome – I really liked mysqli_fetch_assoc() for returning data from the database in a easy to use form – an associate array (in case it wasn’t obvious!). DBAPI drivers for python do not provide such a feature out of the box – your data comes back as a tuple, rather than a dict. While this makes some sense, the lack of a way to get a dict back seems to be rather un-pythonic. It violates the ‘Explicit is better than implicit’ and ‘Beautiful is better than ugly’ Zen of Python aphorisms. It requires implicit accessing of your data, as you must use tuple slices/subscripts instead of keywords to the dict, and that requires ugly numbers dropped into the otherwise easily readable code.

In an effort to save myself some trouble, here’s a quick way to emulate the fetch_assoc functionality, built in to a generator function so it can be used easily in ‘for’ statements and the like:

#!/usr/bin/env python
# Requires a version of python that supports generator functions (2.3+)
import  MySQLdb

connection = MySQLdb.connect(host="localhost", user="username", passwd="passwd", db="myInstance", use_unicode=True, charset="utf8")
cursor = connection.cursor()
def query(query, args):
        numRows = cursor.execute(query, args)
        tries = 0
        dbKeys = cursor.description
        row = {}
        while tries < numRows:
                tries = tries + 1
                dbRow = cursor.fetchone()
                for item, key in zip(dbRow, dbKeys):
                        row[key[0]] = item
                yield row

sql = """SELECT foo, bar FROM baz WHERE id = %(id)s"""
args = {'id':'adam'}

for rows in query(sql, args):
        print rows

That outputs:

	{'foo': u'fooValue', 'bar':'barValue'}
	{'foo': u'fooValue2', 'bar':'barValue2'}

January 15, 2008   7 Comments

HR Geeks

This morning, I launched a new version of the HR Geeks website.  I’m proud to say we now have the only non-hideous, non-1995 website of any geek group in Hampton Roads :)

The site is running WordPress, with a highly hacked up GridFocus theme.  After much debate, and a not-insignificant-delay, I determined that I didn’t have the free time or energy to maintain the site using a custom CMS, or even a pre-built ‘framework’ like Django.  The big scare over a ‘public’ CMS, like WP, is security issues.  Luckily for me, I use WP on a number of other blogs, so keeping track of upgrades and the like is fairly easy to do.

As part of the migration, we also dumped the old PHP Webcalendar system, and moved to a public Google Calendar for all event tracking.  PHP Webcal was a very non-elegant system to use, while Google Calendar provides a superset of the features, with nearly 0 effort on our part.  There is even the possibility that we could grant access to the public calendar for certain groups to modify their own dates.  I’m not sure how access controlled Gcal is  currently (I know you can have multiple editors, but is it free for all for them?), but it’s worth a look.  Having iCal support, now that I’m using OSX full time, is incredibly useful.  The HTML output is substantially prettier than any of the other PHP web calendar’s that I’ve seen so far.

September 19, 2007   2 Comments

When does Spring end…

Helio OceanBecause I really want this phone: The Helio ‘Ocean‘ (review roundup).

As soon as the Ocean comes out (‘Spring 2007′ is the listed date ‘May 21st’, according to interweb news sources now!) I’m going to be switching off of T-mobiles network, and embracing some unfiltered EVDO love. Helio looks like a pretty cool company, and despite being a bit more expensive than Sprint or Verizon straight up, their service and phones are much less hideous, and aimed more at a non-business user. The unified messaging system (single interface for IM/SMS/voice) and the GPS access on the phone itself looks pretty awesome, in the same design line as the visual voicemail on the iPhone. It also has the benefits of syncing calendar/etc from Exchange/Outlook or push-email through services like Hotmail. The dual-slide system also eleminates my major gripe about qwerty keyboard phones – it’s a pain in the ass to dial a phone number, which is still my primary use of a cell phone as low tech as that may sound. Opening the phone up for 3rd party apps would be awesome, and it might be already (I cant’ find evidence either way), but what they claim to be shipping will be enough for me!

May 7, 2007   3 Comments

Velux 5 Oceans


velux5oceans
Went with Chris down to Waterside on Sat. afternoon to check out the Velux 5 Oceans boats that were tied up for stop over before heading to Bilbao, Spain. The boats are incredible – all of them are sailed by a single person, completely around the world (the long way, no pesky canals!). Incredible amounts of technology – all kinds of radar, GPS and SatCom gear, composite materials for masts/hulls, solar panels embedded into the decking. Very neat stuff.

There were no American competitors, which I think is a big part of the extremely low number of people who showed up to see the boats. This place is kind of wack like that, I guess. Hardly anybody showed up for the NATO / AzaleaFest cultural festivities last year either.

April 16, 2007   No Comments

TWUUG Presentation

Permanent page here.

June 24, 2006   No Comments