In applications it is often convenient to be able to save or remember information provided or edited by a user. Whilst sessions often provide a convenient means of remembering such information, they have certain limitations, notably that they are only available to a particular user and cannot be shared with other users, and that their data is stored in a form that is not necessarily convenient to access by other tools or systems.
The principle behind the DirectoryRepository
class is that it stores information as files in a designated directory,
that such files can be accessed by any resource with access to that
directory, and that a certain degree of locking is provided to avoid
contention between resources. Once created, instances of DirectoryRepository
can be accessed almost like sessions, although it is possible to obtain
the full paths to files in the repository and to use file objects and
methods to obtain and deposit content in such files.
The DirectoryRepository
class (found in the WebStack.Repositories.Directory
module) accepts the following parameters when being initialised:
path
fsencoding
delay
One might choose to initialise a repository in the initialisation method of a resource:
# Inside a module defining a resource...
class MyResource:
def __init__(self):
repository_dir = os.path.join(os.path.split(__file__)[0], "repository")
self.repository = DirectoryRepository(repository_dir, "iso-8859-1")
Here, the repository will reside alongside the resource's module in the filesystem.
One might use a repository with a session-like API as follows:
# Given a name and some data, possibly provided in user input, store the data in the repository.
repository[name] = data
Note that DirectoryRepository
places some restrictions on the values that can be used as keys in the
session-like API since each key must correspond to a filename within
the designated directory.
The DirectoryRepository
class also provides various methods to support access to files in the repository using standard file objects and methods:
# Given a name and some data...
edit_path = repository.lock(name)
f = open(edit_path, "wb")
try:
f.write(data)
finally:
f.close()
repository.unlock(name)
The usage of try
and finally
clauses is important to ensure that files are not left locked and
inaccessible due to unhandled exceptions being raised. See the API documentation for the DirectoryRepository
class for more information about the available methods and their behaviour.