Tips, Tricks, and Aerial Flips for Programming

From time to time, I write a fun script or create some neat process or do something that's just plain neat. I keep telling myself to start a blog and document these things... share them with the world, even! Well, here we go.

Wednesday, February 18, 2009

Writing to Files in Google App Engine

In Google App Engine, you can't write to files because everything is clustered and you don't really know where the files are. If you need to write data, you need to write to the datastore. However, during development, it's sometimes helpful to be able to write files. For instance, suppose you have a huge site with a large number of style definitions and you want them spread out across multiple files to make them easier to manage, but when you go to release, you want just one file that holds everything sent over to the client in order to minimize the number of http connections. Suppose you also want to minify this file so it takes up less room in the user's cache and uses less bandwidth too send.

By enabling file writes during development, you can easily compress/minify/interpret/etc copies of your working files on-the-fly as you're developing. Just be careful this code doesn't run live -- I have no idea what will happen.

def writefile(filepath, content):
  from google.appengine.tools import dev_appserver
  
  # Store the modes that GAE allows
  allowed_modes = dev_appserver.FakeFile.ALLOWED_MODES
  
  # Overwrite the modes with the write-binary mode
  dev_appserver.FakeFile.ALLOWED_MODES = frozenset(['wb'])
  
  # Open the file, write the content to it, and close the file handle
  f = open(filepath, 'wb')
  f.write(content)
  f.close()
  
  # Restore GAE's allowed file modes
  dev_appserver.FakeFile.ALLOWED_MODES = allowed_modes