Tuesday, 8 May 2012

Something old, something new, something borrowed...


I'm dedicating this post to some new and borrowed things I've been looking at recently. I found myself in a bit of a rut lately, using some of the same old techniques over and over again, instead of looking at the better, more efficient methods that are out there.

Something old:
One thing I've tried to overcome is a bad habit of using Javascript alerts to tell me what's going on with variable values in web pages. Mainly just because it's convenient. Instead, now I'm using Firebug (the debugger add-on for the Firefox browser) and the console.log command regularly to check values. I'm also getting better at using the Script tab in there for stepping through functions and loops, etc. I can't believe I haven't been using these for so long, it only took a few short moments to realise the folly of my ways. (I had known about these features for a long time, but foolishly ignored them.)

Something new:
In Python, another thing I've been deploying more and more has been filters and list comprehensions. As well as being great space-savers in your code, they seem to run in programs more quickly too. Here's one I wrote to process a dict, retrieving the first key who value matches an if condition. The dict "users_to_find" has a value, "v", somewhere that matches what is in my row[2] tuple.

user_name = [k for k, v in users_to_find.items() if v == row[2]][0]

Goodbye YA boring "for/if/break" loop! :-D

Something borrowed:
The last thing I'll mention is a little script I'm having to make which will retrieve old historical data from a MySQL database. Previously, the project that stored the data was using the heavyweight Python SQLAlchemy ORM library. Obviously, my small script doesn't need overkill in this fashion, so I'm borrowing the basic MySQLdb library to do this instead.

My experience moving from a sophisticated ORM to a simpler database interface module has been interesting. My queries in SQLAlchemy had involved much use of backrefs, retrieving from lists stored in objects, and joins. Now, just to get one value from one table linked to two others, I'm having to build SQL command strings like this:

sql_cmd = """select code from service
join service_sale
on service_sale.service_id = service.res_id
join sale
on sale.res_id = service_sale.sale_id
where sale.res_id = 693764;"""

What's going to make it clunky and complicated is that I have a few more "where" conditions to add on top of there, and also have to retrieve all the fields from the sale table. And in a moment of insanity earlier I had put an associative table, "service_sale", between two other tables. There's nothing like a good challenge. I guess I might have finished my mission (retrieving historical data from the old project) faster if I had just stuck with the old ORM queries. But it's great getting your hands dirty with barebones SQL now and again.

No comments:

Post a Comment