Documentation for repoze.filesafe


repoze.filesafe provides utilities methods to safely handle creation of files on the filesystem by integrating with the ZODB package’s transaction manager. It can be used in combination with (or repoze.tm2) for use in WSGI environments. More information about using a transaction manager can be found in the Using a Transaction-Aware Data Manager Under article.

Purpose and Usage

The ZODB transaction manager is a completely generic transaction manager. It can be used independently of the actual “object database” part of ZODB, for example to integrate the transaction handling of SQL servers with your application. repoze.filesafe allows you to create files within a transaction. If the transaction is aborted the files will be removed, prevention any leftovers from polluting your disk.

Creating a file works very similar to the standard python open call:

from repoze.filesafe import create_file

f = create_file("/some/path", "w")
f.write("Hello, World!")

This will create a new temporary file and write your data to it. Once the transaction is commited it will move the file to the path name you specified. If the transaction is aborted the temporary file will be removed.

repoze.filesafe assumes that temporary files will be on the same filesystem as the target path. The default location is determined by the python tempfile module. You may need to configure a different path if you use a separate filesystem for /tmp using the TMPDIR environment variable.

It is possible to (re)open a file that has not been been commited yet using the open_file method:

from repoze.filesafe import create_file, open_file

f = create_file("/some/path", "w")
f.write("Hello, World!")

f = open_file("/some/path")

This will print the greeting that was stored in the file. If open_file is called with a path that has not been created using create_file in the current transaction it will be opened normally, as if the standard open method was used.

You can also delete files with delete_file.

Unit tests

repoze.filesafe.testing provides several utility methods to facilitate unit testing of code which uses repoze.filesafe:

Integration repoze.filesafe with transactions

Earlier repoze.filesafe versions required usage of a WSGI middleware or manual hooking into the transaction logic. Since repoze.filesafe 2 this is no longer required.

The WSGI middleware is still available for backwards compatibility, but no longer does anything.

Indices and tables

Table Of Contents

Next topic

Change History

This Page