Tag Archives: python

More Python features that I really like

Another thing that makes using [Python][python] pleasing is decorators. [A decorator is a wrapper for a function][decorators] (or method) that takes a function (or method) as an argument and returns a new function (or…) which is then bound to the name for the original function.

The newly-decorated function can then do things like checking the called arguments before invoking the original un-decorated function.

[Django provides decorators for authentication][django] so that you can wrap a view function with a check for client credentials before deciding whether to return the original response or a deny access.

In this manner Django’s authentication decorators encourage orthogonal code: the logic for displaying a view is separated from the logic for deciding whether you should be permitted to see the view’s output. By keeping them separate, it becomes simpler to re-use the authentication logic and apply it to other views.

Suppose you have a view that accepts [a Django request object][request] and checks whether the user is signed in:

def administration_page(request):
if request.user.is_authenticated():
return HttpResponse(“Welcome, dear user.”)
else:
return HttpResponseRedirect(“/signin/”)

With a decorator you can simplify and clarify things:

@login_required
def administration_page(request):
return HttpResponse(“Welcome, dear user.”)

For older versions of Python (pre 2.4) [which don’t understand the `@` operator][syntax] one must explicitly decorate the view function like so:

def administration_page(request):
return HttpResponse(“Welcome, dear administrator.”)

administration_page = login_required(administration_page)

Note in the example that the original `administration_page` function is passed to the decorator. The `@` syntax in the first example makes that implicit but the two are equivalent.

The implementation of a decorator is interesting. It takes the function itself as an argument and returns a new function which does the actual checking. Here is how the decorator used above might do its stuff:

def login_required(view_function):
def decorated_function(request):
if request.user.is_authenticated():
return view_function(request)
else:
return HttpResponseRedirect(“/signin/”)

return decorated_function

_The actual [implementation of Django’s `login_required` decorator][login_required] is considerably less idiotic. Python’s [functools module][functools] has helpers for writing well-behaved decorators._

Because functions in Python are themselves objects the decorator can accept a function reference, construct a new function that checks for authentication and then return a reference to that new function.

Simples!

(Simples gets less simples when you want to write a decorator that accepts configuration arguments because you then need either another layer of nested function definitions or a class whose instances can be called directly, but I’m going to ignore you for a bit and _wow is that Concorde…?_)

[python]: http://www.python.org
[decorators]: http://docs.python.org/reference/compound_stmts.html#function
[django]: http://docs.djangoproject.com/en/dev/topics/auth/#django.contrib.auth.decorators.user_passes_test
[request]: http://docs.djangoproject.com/en/dev/ref/request-response/
[syntax]: http://docs.python.org/whatsnew/2.4.html#pep-318-decorators-for-functions-and-methods
[functools]: http://docs.python.org/library/functools.html
[login_required]: http://code.djangoproject.com/browser/django/tags/releases/1.2.1/django/contrib/auth/decorators.py

Split a file on any character in Python

I need to split a big text file on a certain character. I expect I am being thick about this, but [`split`][split] doesn’t quite do what I want because it includes the matching line, whereas I want to split right on the matching character.

My Python answer:

def readlines(filename, endings, chunksize=4096):
“””Returns a generator that splits on lines in a file with the given
line-ending.
“””
line = ”
while True:
buf = filename.read(chunksize)
if not buf:
yield line
break

line = line + buf

while endings in line:
idx = line.index(endings) + len(endings)
yield line[:idx]
line = line[idx:]

if __name__ == “__main__”:
import sys, os

FORMFEED = chr(12) # ASCII 12
basename = os.path.basename(sys.argv[1])
for num, data in enumerate(readlines(open(sys.argv[1]), endings=FORMFEED)):
filename = basename + ‘-‘ + str(num)
open(filename, ‘wb’).write(data)

This is also useful when reading data exported from some old-fashioned Mac application like [Filemaker 5][filemaker] where the line-endings are ASCII 13 not ASCII 10.

This post was inspired by [Lotus Notes][lotus] version 8.5, which is so advanced that to save a message in a file on disk you have to export it as structured text. And if you want to save a whole bunch of messages as individual files you must forget that [drag-and-drop was introduced with System 7][mactech], that would be too obvious.

[filemaker]: http://www.filemaker.com/support/downloads/downloads_prev_versions.html
[split]: http://developer.apple.com/Mac/library/documentation/Darwin/Reference/ManPages/man1/split.1.html
[lotus]: http://www-01.ibm.com/software/lotus/products/notes/
[mactech]: http://www.mactech.com/articles/mactech/Vol.10/10.06/DragAndDrop/index.html

Django AdminForm objects and templates

I can’t find documentation for the context of a Django admin template. In particular, where is the form and how does one access the fields? This post describes the template context for a generic admin model for [Django 1.1][django11].

Django uses an instance of `ModelAdmin` (defined in [`django.contrib.admin.options`][options]) to handle the request for a model object add / change view in the admin site. `ModelAdmin.add_view` and `ModelAdmin.change_view` are responsible for populating the template context when rendering the add object and change object pages respectively.

Here are the keys common to add and change views:

– **title**, ‘Add ‘ or ‘Change ‘ + your model class’ `_meta.verbose_name`
– **adminform** is an instance of `AdminForm`
– **is_popup**, a boolean which is true when `_popup` is passed as a request parameter
– **media** is an instance of [`django.forms.Media`][media]
– **inline_admin_formsets** is a list of [`InlineAdminFormSet`][inlineset] objects
– **errors** is an instance of [`AdminErrorList`][errors]
– **root_path** is the `root_path` attribute of the `AdminSite` object
– **app_label** is your model class’ `_meta.app_label` attribute

The way that Django renders a form in the admin view is to iterate over the `adminform` instance and then iterate over each [`FieldSet`][fieldset] which in turn yield [`AdminField`][adminfield] instances. All I want to do is layout the form fields, ignoring the fieldset groupings which may or may not be defined in the model’s `ModelAdmin.fieldset` attribute.

This turns out to be easy once you know how. The regular form is an attribute of the `adminform` object. So if your model has a field named “`king_of_pop`” you can refer to the form field in your template like so:

{{ adminform.form.king_of_pop.label_tag }}: {{ adminform.form.king_of_pop }}

Or if you want to save your finger tips you can use the [`with` template tag][with]:

{% with adminform.form as f %}
{{ f.king_of_pop.label_tag }}: {{ f.king_of_pop }}
{% endwith %}

Delving through the Django source while I tried to understand all of this I was struck by how [Python defines hook functions for iteration and accessing attributes][hooks]. Half of Python’s attraction is in how easy it is from the program author’s point of view to treat objects as built-in types like lists, dicts, etc.; the other half is the responsibility of the author of a Python module to encourage that same ease of use by implementing the related iteration protocols. It is harder to write a good Python module than it is to write a good Python program that uses a good module.

[django11]: http://code.djangoproject.com/browser/django/tags/releases/1.1
[options]: http://code.djangoproject.com/browser/django/tags/releases/1.1/django/contrib/admin/options.py#L175
[fieldset]: http://code.djangoproject.com/browser/django/tags/releases/1.1/django/contrib/admin/helpers.py#L50
[adminfield]: http://code.djangoproject.com/browser/django/tags/releases/1.1/django/contrib/admin/helpers.py#L82
[with]: http://docs.djangoproject.com/en/dev/ref/templates/builtins/#with
[media]: http://docs.djangoproject.com/en/dev/topics/forms/media/
[inlineset]: http://code.djangoproject.com/browser/django/tags/releases/1.1/django/contrib/admin/helpers.py#L102
[errors]: http://code.djangoproject.com/browser/django/tags/releases/1.1/django/contrib/admin/helpers.py#L198
[hooks]: http://docs.python.org/reference/datamodel.html#emulating-container-types

Using MacPorts behind a firewall

I failed to persuade [MySQLdb][mysqldb] to build on a [Mac OS X Server 10.5.8][1058] install using the system [Python][python] + [MySQL][mysql] installation. So I turned to [MacPorts][macports] where I know I can get [Django][django] + all the bits working without much hassle (but with much patience).

The next problem was that MacPorts couldn’t update because [rsync][rsync] was blocked by the corporate access policy. Fortunately plain HTTP is permitted outbound. Here’s how to use a local ports tree.

Install MacPorts using the disk image for 10.5.

curl -O http://distfiles.macports.org/MacPorts/MacPorts-1.8.2-10.5-Leopard.dmg
hdiutil attach MacPorts-1.8.2-10.5-Leopard.dmg
sudo installer -pkg /Volumes/MacPorts-1.8.2/MacPorts-1.8.2.pkg -target /
hdiutil detach /Volumes/MacPorts-1.8.2

If the MacPorts install directories are not in your $PATH environment, you can add them to your `.profile`. This change will not take effect until you start a new terminal session.

*(Updated to keep variables as-is as suggested by commenter Bruce).*

cat >> ~/.profile <<\EOF PATH=/opt/local/bin:/opt/local/sbin:${PATH} MANPATH=/opt/local/share/man:${MANPATH} EOF After you have installed MacPorts, create a directory for the ports tree and check it out using [Subversion][svn]. sudo mkdir -p /opt/local/var/macports/sources/svn.macports.org/trunk/dports cd /opt/local/var/macports/sources/svn.macports.org/trunk/dports sudo svn co http://svn.macports.org/repository/macports/trunk/dports/ . N.B. In the last line beginning `svn co ...` the trailing directory separator is significant! Now tell MacPorts to use the local checkout rather than rsync. Edit `/opt/local/etc/macports/sources.conf` and add a new line to the end with the path to the ports tree, then comment out the previous line that uses rsync. Here are the last lines from my configuration: #rsync://rsync.macports.org/release/ports/ [default] file:///opt/local/var/macports/sources/svn.macports.org/trunk/dports/ [default] Finally you must create an index for the tree (otherwise you will see messages saying "Warning: No index(es) found!"). cd /opt/local/var/macports/sources/svn.macports.org/trunk/dports sudo portindex Now go do great things. [mysqldb]: http://mysql-python.sourceforge.net/MySQLdb.html [macports]: http://www.macports.org/ [1058]: http://www.apple.com/server/macosx/ [mysql]: http://www.mysql.com/ [python]: http://www.python.org/ [django]: http://www.djangoproject.com/ [rsync]: http://samba.anu.edu.au/rsync/ [svn]: http://subversion.tigris.org/

ModelForms good for importing too

If you have exported data from one database in plain text format and you want to import it to [Django][django], you should use a [`ModelForm` class][modelform] to do a lot of the heavy lifting for you.

A suitable `ModelForm` for your Django model will consume each row and do the conversion of each field to an appropriate Python type. Much simpler than explicitly converting each value yourself before creating a new model instance.

Suppose you have a model for an address book entry and its associated `ModelForm` (this works for Django 1.1):

# myapp/models.py
from django.db import models
from django import forms

class Contact(models.Model):
first_name = models.CharField(max_length=100)
second_name = models.CharField(max_length=100)
telephone = models.CharField(max_length=50, blank=True)
email = models.EmailField(blank=True)

class ContactForm(forms.ModelForm):
class Meta:
model = Contact

Here’s a script to run through a comma-separated list of contacts where each line looks something like “Smits, Jimmy, [email protected], 555-1234”:

from myapp.models import ContactForm

# Map columns to fields, adjusting the order as necessary
column_map = (
‘second_name’,
‘first_name’,
’email’,
‘telephone’,
)

for line in open(‘tab-separated-data.txt’):
row = dict(zip(column_map, (field.strip() for field in line.split(‘,’))))
form_obj = ContactForm(row)
try:
form_obj.save()
except ValueError:
for k, v in form_obj.errors.items():
print k, row[k], ‘, ‘.join(map(unicode, v))

If a line doesn’t validate the script prints the validation errors and moves to the next line. If your data has columns you want to ignore then just name them in the `column_map` – the form class will ignore extra keys in the dictionary.

[django]: http://www.djangoproject.com
[modelform]: http://docs.djangoproject.com/en/dev/topics/forms/modelforms/

Notes on Radmind’s checksum

It would be nice to do a [pure-Python][python] implementation of [Radmind][radmind]’s fsdiff output for [watchedinstall][watchedinstall], which consists of several white-space separated fields describing the filename’s attributes and an optional checksum for the file.

These are notes on how Radmind generates checksums for files on [Mac OS X][macosx].

The [fsdiff format is documented][manfsdiff], however for files with Mac Finder info or a resource fork the checksum is for an [AppleSingle][applesingle]-encoded representation of the file, which means a Python implementation needs to produce an equivalent AppleSingle-encoded byte stream for the file. Bummer.

Python 2.6 on Mac OS X includes a [(deprecated) applesingle module][applesinglemod] that can read the format but cannot write it (and the module has been removed for Python 3). Therefore a pure Python implementation of Radmind’s checksum has to implement a compatible AppleSingle encoding routine too.

Radmind’s fsdiff command is written in C, which I can just about get the gist of, but I am missing something because my attempts at emulating Radmind’s checksums are wrong.

The meat of Radmind’s checksum is the [`do_acksum()` function in `cksum.c`][cksum]. The algorithm appears to be as follows:

1. Initialize a digest using the default cipher ([MD5][md5] I think).
2. Add the AppleSingle header, consisting of a magic number and version number and some padding.
3. Add the AppleSingle entry table, which has 3 entries for the Finder info, the resource fork info and the data fork info (in that order). Each entry is 12 bytes – an unsigned long for the entry type, an unsigned long for an offset into the file where the data will start and an unsigned long for the data length.
4. Add the Finder info data.
5. Add the resource for data.
6. Add the data fork data.
7. Return a base64 encoded version of the final digest.

Because the entry table in the AppleSingle header specifies data offsets and lengths you need to know the size of the Finder info data (always 32 bytes) and the size of the resource fork and the size of the data fork before you pass that data to the digest function.

So a working Python implementation needs to know the size of the resource fork and data fork before feeding that same data to the digest. It seems to me that this requirement might imply huge memory allocations while slurping file data – my wrong attempt tried counting bytes and later feeding the same data to the digest in manageable chunks.

Anyway…

Advice much appreciated. The workaround is to leave it to fsdiff to generate the checksum and parse the value from the output.

David

P.S. I still intend running [A/UX 3.0.1][aux] on my Centris 660av one day.

Update: using my eyes and brains and the `fsdiff -V` command I was able to read the fsdiff man page and deduce the preferred checksum cipher is actually sha1. My code is still wrong.

[radmind]: http://rsug.itd.umich.edu/software/radmind/
[python]: http://www.python.org/
[macosx]: http://www.apple.com/macosx/
[manfsdiff]: http://linux.die.net/man/1/fsdiff
[applesingle]: http://users.phg-online.de/tk/netatalk/doc/Apple/v2/AppleSingle_AppleDouble.pdf
[applesinglemod]: http://www.python.org/doc/2.6.2/library/undoc.html#module-applesingle
[md5]: http://www.openssl.org/docs/crypto/md5.html
[aux]: http://www.aux-penelope.com/
[cksum]: http://radmind.cvs.sourceforge.net/viewvc/radmind/radmind/cksum.c
[watchedinstall]: http://bitbucket.org/ptone/watchedinstall/

Context managers

I was re-writing the exellent [watchedinstall][watchedinstall] tool and needed to simplify a particularly gnarly chunk of code that required three sub-proceses to be started and then killed after invoking another process. It occurred to me I could make these into context managers.

Previously the code was something like…

start(program1)
try:
start(program2)
except:
stop(program1)
raise

try:
start(program3)
except:
stop(program2)
stop(program1)
raise

try:
mainprogram()
finally:
stop(program3)
stop(program2)
stop(program1)

Of course that could have been written with nested try / except / else / finally blocks as well, which I did start with but found not much shorter while almost incomprehensible.

[With context managers][ctxt] the whole thing was written as…

# from __future__ import with_statement, Python 2.5

with start(program1):
with start(program2):
with start(program3):
mainprogram()

So much more comprehensible! Here’s the implementation of the context manager (using the `contextlib.contextmanager` decorator for a triple word score):

import contextlib
import os
import signal
import subprocess

@contextlib.contextmanager
def start(program_args):
prog = subprocess.Popen(program_args)
if prog.poll(): # Anything other than None or 0 is BAD
raise subprocess.CalledProcessError(prog.returncode, program_args[0])

try:
yield
finally:
if prog.poll() is None:
os.kill(prog.pid, signal.SIGTERM)

For bonus points I might have used [`contexlib.nested()`][ctxtlib] to put the three `start()` calls on one line but then what would I do for the rest of the day?

[watchedinstall]: http://bitbucket.org/ptone/watchedinstall/
[ctxt]: http://docs.python.org/library/stdtypes.html#typecontextmanager
[ctxtlib]: http://docs.python.org/library/contextlib.html

I am very bad at writing tests

… but I _think_ I might be getting a little better.

At least these days when I am writing some script (almost certainly in [Python][python]) I start out by intending to write tests. I usually fail because I haven’t learnt to think in terms of writing code that can be easily tested.

[Mark Pilgrim][pilgrim]’s [Dive Into Python][dive] has great stuff on how to approach a problem by [defining the tests first and gradually filling in the code][divetest] that satisfies the test suite. One day I may be able to work like that, until then I work by writing a concise docstring, then stubbing out the function. Once the function is in a state where it might actually return a meaningful result I can play with it in the Python interpreter and start adding useful [doctests][doctest] to the [docstring][docstring].

What really helps is to break the logic out into tiny pieces where ideally each piece returns the result of transforming the input (which I think is known as a [functional approach][functional]). By doing this I can have tests for most of the code and those functions that have a lot of conditional logic, those functions that are harder to write tests for, will at least be relying on sub-routines that are themselves well tested.

I can dream.

[python]: http://www.python.org/
[pilgrim]: http://diveintomark.org/
[dive]: http://www.diveintopython.org/
[divetest]: http://diveintopython.org/unit_testing/stage_1.html
[doctest]: http://docs.python.org/library/doctest.html
[functional]: http://en.wikipedia.org/wiki/Functional_programming
[docstring]: http://www.python.org/dev/peps/pep-0257/

Crazy Acrobat installers love Python

Looking through the updaters for [Adobe Acrobat][acrobat] 9 for Mac I came across a bunch of scripts written in [Python][python]. My favourte was called `FindAndKill.py`:

#!/usr/bin/python
“””
Search for and kill app.
“””
import os, sys
import commands
import signal

def main():
if len(sys.argv) != 2:
print ‘Missing or too many arguments.’
print ‘One argument and only one argument is required.’
print ‘Pass in the app name to find and kill (i.e. “Safari”).’
return 0

psCmd = ‘/bin/ps -x -c | grep ‘ + sys.argv[1]
st, output = commands.getstatusoutput( psCmd )

if st == 0:
appsToKill = output.split(‘\n’)
for app in appsToKill:
parts = app.split()
killCmd = ‘kill -s 15 ‘ + parts[0]
#print killCmd
os.system( killCmd )

if __name__ == “__main__”:
main()

(You can [download the Acrobat 9.1.3 update][acrobat913] and find this script at `Acrobat 9 Pro Patch.app/Contents/Resources/FindAndKill.py`.)

Was the author not aware of the `killall` command for sending a kill signal to a named process? The [`killall` man page][mankillall] says it appeared in [FreeBSD 2.1, which was released in November 1995][fbsd]. Adobe CS4 was [released about 14 years later][cs4]. How is it Adobe’s product managers approve these things for release?

What is particularly galling about Adobe’s Acrobat 9 updaters is that they seem to re-implement so much of what the Apple installer application does, even down to their use of gzipped cpio archives for the payload.

[acrobat913]: http://www.adobe.com/support/downloads/detail.jsp?ftpID=4538
[acrobat]: http://www.adobe.com/products/acrobatpro/
[python]: http://www.python.org
[mankillall]: http://www.manpagez.com/man/1/killall/
[fbsd]: http://www.freebsd.org/releases/2.1R/announce.html
[cs4]: http://www.adobe.com/aboutadobe/pressroom/pressreleases/200809/092308AdobeCS4Family.html

Migrating a Filemaker database to Django

At work we have several [Filemaker Pro][fmp] databases. I have been slowly working through these, converting them to Web-based applications using [the Django framework][django]. My primary motive is to replace an overly-complicated Filemaker setup running on four Macs with a single 2U rack-mounted server running [Apache][apache] on [FreeBSD][fbsd].

At some point in the process of re-writing each database for use with Django I have needed to convert all the records from Filemaker to Django. There exist good [Python][python] libraries for [talking to Filemaker][pyfmp] but they rely on the XML Web interface, meaning that you need Filemaker running and set to publish the database on the Web while you are running an import.

In my experience [Filemaker’s built-in XML publishing interface][fmpxml] is too slow when you want to migrate tens of thousands of records. During development of a Django-based application I find I frequently need to re-import the records as the new database schema evolves – doing this by communicating with Filemaker is tedious when you want to re-import the data several times a day.

So my approach has been to export the data from Filemaker as XML using [Filemaker’s FMPXMLRESULT][fmpxmlresult] format. The Filemaker databases at work are _old_ (Filemaker 5.5) and perhaps things have improved in more recent versions but Filemaker 5/6 is a very poor XML citizen. When using the FMPDSORESULT format (which has been dropped from more recent versions) it will happily generate invalid XML all over the shop. The FMPXMLRESULT format is better but even then it will emit invalid XML if the original data happens to contain funky characters.

So here is [filemaker.py, a Python module for parsing an XML file produced by exporting to FMPXMLRESULT][dave] format from Filemaker.

To use it you create a sub-class of the `FMPImporter` class and over-ride the `FMPImporter.import_node` method. This method is called for each row of data in the XML file and is passed an XML node instance for the row. You can convert that node to a more useful dictionary where keys are column names and values are the column values. You would then convert the data to your Django model object and save it.

A trivial example:

import filemaker

class MyImporter(filemaker.FMPImporter):
def import_node(self, node):
node_dict = self.format_node(node)
print node[‘RECORDID’], node_dict

importer = MyImporter(datefmt=’%d/%m/%Y’)
filemaker.importfile(‘/path/to/data.xml’, importer=importer)

The `FMPImporter.format_node` method converts values to an appropriate Python type according to the Filemaker column type. Filemaker’s `DATE` and `TIME` types are converted to Python [`datetime.date`][dtdate] and [`datetime.time`][dttime] instances respectively. `NUMBER` types are converted to Python `float` instances. Everything else is left as strings, but you can customize the conversion by over-riding the appropriate methods in your sub-class (see the source for the appropriate method names).

In the case of Filemaker `DATE` values you can pass the `datefmt` argument to your sub-class to specify the date format string. See Python’s [time.strptime documentation][strptime] for the complete list of the format specifiers.

The code uses [Python’s built-in SAX parser][pysax] so that it is efficent when importing huge XML files (the process uses a constant 15 megabytes for any size of data on my Mac running Python 2.5).

Fortunately I haven’t had to deal with Filemaker’s repeating fields so I have no idea how the code works on repeating fields. Please let me know if it works for you. Or not.

[Download filemaker.py][dave]. This code is released under a 2-clause BSD license.

[dave]: http://reliablybroken.com/b/wp-content/uploads/2009/11/filemaker.py
[strptime]: http://docs.python.org/library/time.html#time.strftime
[fmp]: http://www.filemaker.com/
[django]: http://www.djangoproject.com/
[apache]: http://httpd.apache.org/
[fbsd]: http://www.freebsd.org/
[python]: http://www.python.org/
[pyfmp]: http://code.google.com/p/pyfilemaker/
[fmpxml]: http://www.filemaker.com/support/technologies/xml
[fmpxmlresult]: http://www.filemaker.com/help/html/import_export.16.30.html#1029660
[dtdate]: http://docs.python.org/library/datetime.html#date-objects
[dttime]: http://docs.python.org/library/datetime.html#time-objects
[pysax]: http://docs.python.org/library/xml.sax.html