I wrote a smaller test case to trigger the bug and it turned out that there was more to the problem than this.
The second problem is that the open statement is done outside the lock, and that will truncate the file. To solve the issue you need to lock the file before the open statement. I have made a solution with test case on github and issued a pull request for it: https://github.com/mdipierro/web2py/pull/5 In my solution I have removed the unlocks and only use close and that seems to work fine.

