The following is an example of how you can write and read from the same temporary file handler in Python.

# Create a temp file to write to
temp_file = tempfile.TemporaryFile()

for doc in docs:
    # Write documents to tempfile
    temp_file.write(json.dumps(doc, default = dthandler))

# Reset the seeker

for line in temp_file.readlines():
    print line

Writing a note here about how to print the all fields from number n to the end with awk. It might be useful for someone else sometime.

awk 'BEGIN{ FS="-" }{ print substr($0, index($0,$3)) }'

That would match going-on-in-here in the following string


Here’s a little function to verify if an element exists in a Bash array.

function elementExists() {
    for i in ${elements[@]} ; do
        if [ $i == $element ] ; then
            return 1
    return 0

It takes an array as first argument and the element as the second and will return 1 if the element exists in the array. You can now call the function like this:

elementExists my_array my_element

I ran into a problem with Django’s unique_together feature earlier. The thing is that unique_together validates on the database level and thus the errors does not seem to be propagated to the forms validation properly.

For me that resulted in a form that was completed with no errors communicated to the user, but the data was not saved to database.

Here’s a solution for the problem, where I clean the data my self and throw an error if needed.

You can then handle the form in the view just as usual with like below.

If your’e hacking in many Python projects in parallell you will sooner or later run in to a Python package hell. The different projects might need different versions of Python or some package. I have also found it comfortable to know what packages the code I develop on actually depends on. A wonderful solution for this kind of problems is virtualenv.

virtualenv allows you to have a totally isolated Python environment for each of your projects.

sudo pip install virtualenv
cd /your/project-1
virtualenv virtualenv
source virtualenv/bin/activate

Your PS1 in Bash will now look something like this:

(virtualenv)[sebastian ~/git/git-hall-of-fame (master)]$

So anything you install via pip or easy_install now will be installed for this virtualenv only.

I have one virtualenv for each of my projects inside the git structure, and then I add virtualenv to .gitignore to keep the changes locally.