4.6.2 FieldStorage Examples

##
4.6.2 FieldStorage Examples

The following examples demonstrate how to use the file_callback parameter of the `FieldStorage` constructor to control file object creation. The `Storage` classes created in both examples derive from FileType, thereby providing extended file functionality.

These examples are provided for demonstration purposes only. The issue of temporary file location and security must be considered when providing such overrides with mod_python in production use.

Simple file control using class constructor

  This example uses the `FieldStorage` class constructor to create the file object, allowing simple control. It is not advisable to add class variables to this if serving multiple sites from apache. In that case use the factory method instead.

      class Storage(file):

          def __init__(self, advisory_filename):
              self.advisory_filename = advisory_filename
              self.delete_on_close = True
              self.already_deleted = False
              self.real_filename = '/someTempDir/thingy-unique-thingy'
              super(Storage, self).__init__(self.real_filename, 'w+b')

          def close(self):
              if self.already_deleted:
                  return
              super(Storage, self).close()
              if self.delete_on_close:
                  self.already_deleted = True
                  os.remove(self.real_filename)

      request_data = util.FieldStorage(request, keep_blank_values=True, file_callback=Storage)

Advanced file control using object factory

  Using a object factory can provide greater control over the constructor parameters.

      import os

      class Storage(file):

          def __init__(self, directory, advisory_filename):
              self.advisory_filename = advisory_filename
              self.delete_on_close = True
              self.already_deleted = False
              self.real_filename = directory + '/thingy-unique-thingy'
              super(Storage, self).__init__(self.real_filename, 'w+b')

          def close(self):
              if self.already_deleted:
                  return
              super(Storage, self).close()
              if self.delete_on_close:
                  self.already_deleted = True
                  os.remove(self.real_filename)

      class StorageFactory:

          def __init__(self, directory):
              self.dir = directory

          def create(self, advisory_filename):
              return Storage(self.dir, advisory_filename)

      file_factory = StorageFactory(someDirectory)
      [...sometime later...]
      request_data = util.FieldStorage(request, keep_blank_values=True,
                                      file_callback=file_factory.create)