This is a very quick tip since it’s so simple but I did run into one little wrinkle with string encoding while doing this so I thought I’d share.
I had a request to generate a CSV of all the Old Dog Haven “Walk for Old Dogs” registrants so the fine folks managing the event can do email blasts, print registration sheets, and the like.
Since Python has CSV functionality as part of the standard library the generation of the CSV data was very easy, and since the Django HTTP Response object was quite wisely designed to behave as a file-like object, writing the CSV data to the HTTP response was dead simple as well.
The only thing I ran into while writing the data to the response object was there were some non-ASCII characters in the database which threw this error:
‘ascii’ codec can’t encode character u’xe9′ in position 4: ordinal not in range(128)
To get around this it was just a matter of tacking .encode(‘utf-8’) to the end of the string objects when writing out the CSV data.
Here’s the final result.