class Pic(static.Data):
"""Runs a db query for id, and either 1) retrieves the file name,
resizes, and provides image/jpeg, or 2) provides an error as
text/plain. This class really shouldn't derive from static.Data,
but instead delegate to it, because it's dynamic."""
def __init__ (self, id):
def fail (err):
self.data = str (err)
self.type = 'text/plain'
def succeed (res):
if len (res) == 0:
fail ('No pic for %s' % id)
return
fn = res[0][0]
im = Image.open (itis_if.prefix + fn) # XXX
new_width = 600
new_sz = (new_width, (new_width * im.size [1]) / im.size [0])
im = im.resize (new_sz)
fil = StringIO()
im.save (fil, "JPEG")
del im
self.data = fil.getvalue ()
self.type = 'image/jpeg'
query = 'SELECT filename FROM pics WHERE id = %s' % (id,)
self.deferred = (
itis_if.dbpool.runQuery (query).addCallbacks (succeed, fail))
def renderHTTP (self, request):
if self.deferred.called:
return static.Data.renderHTTP (self, request)
else:
finished = defer.Deferred ()
finished.addBoth (lambda s: self.renderHTTP (request))
self.deferred.chainDeferred (finished)
return finished