Divmod : Axiom

How to handle files in Axiom?

axiom.store.Store.newFile method returns an axiom.store.AtomicFile? instance - a file, which is initially located in a temporary area, and is moved into final directory when it is closed:

>>> from axiom.store import Store
>>> s = Store('foobar')
>>> f = s.newFile('this', 'is', 'a', 'test')
>>> f
<open file '/usr/home/dotz/foobar/temp/0.tmp', mode 'w+b' at 0x8faef4c>
>>> type(f)
<class 'axiom.store.AtomicFile'>
>>> f.write('123')
>>> f.close()
<Deferred at 0x888440c  current result: FilePath('/usr/home/dotz/foobar/files/this/is/a/test')>
>>> f.finalpath
FilePath('/usr/home/dotz/foobar/files/this/is/a/test')

In some use cases it is desired to have a file resource associated with a given item. So, for example:

import os

from axiom.item import Item
from axiom.attributes import text

class MyItem(Item):
  fname = text()

  def getPath(self):
    return self.store.filesdir.child('myitems').child(self.storeID).child(self.fname)

  def newFile(self):
    '''Return an AtomicFile with path to my file resource.'''
    return self.store.newFile(*tuple(os.path.split(self.getPath().path)))

In some cases it may be even useful to remove this item, together with the file resource, at some time. This is not a transaction-safe operation and you may end up with an inconsistent database - you have been warned.

Let's extend MyItem? class. As we choose to keep file path relative to store.filesdir, we need to access this attribute. Unfortunatley, current Axiom implementation sets self.store to None before Item.deleted callback, so we need to preserve the path somewhere:

from axiom.attributes import inmemory

class MyItem(Item):

  ...

  _path = inmemory()

  ...

  def deleteFromStore(self, *args, **kw):
    self._path = self.getPath().path
    return Item.deleteFromStore(self, *args, **kw)

  def deleted(self):
    os.unlink(self._path)

jethro@divmod.org