My guess is that what you were assuming/hoping is that the result of the filter_by query contains a dictionary mapping the images retrieved to their ids. Instead it holds a query object which represents a promise to return an iterable result set when it is forced to by an access to either a slice expression like Alex mentioned or an iteration operation.
This probably isn't the best way to solve this problem, but my guess is that modifying your code to look like this will probably accomplish what you want:
def get_image(self, userid, id):
image = meta.Session.query(Image).filter_by(userid=userid)
image = dict((img.id, img) for img in image)
permanent_file = open(image[id].image_path, 'rb')
if not os.path.exists(image.image_path):
return 'No such file'
data = permanent_file.read()
permanent_file.close()
response.content_type = guess_type(image.image_path)[0] or 'text/plain'
return data
The more sensible way would be something like this:
def get_image(self, userid, id):
image = meta.Session.query(Image).filter_by(userid=userid).filter_by(id=id).first()
# TODO: Handle the case when image is None
permanent_file = open(image[id].image_path, 'rb')
if not os.path.exists(image.image_path):
return 'No such file'
data = permanent_file.read()
permanent_file.close()
response.content_type = guess_type(image.image_path)[0] or 'text/plain'
return data
Of course you're assuming that an image exists that matches the query and it may not, so you should probably have some error handling for that where I left the TODO comment.
Of course any of these changes will only return the data for a single image. If you want multiple images, you're going to have to call this function once for each image, probably in the request handler for some sort of image view.
If you really do want to return the raw image data for multiple images at once, then Alex's suggestion to use slicing to get back e.g. 10 records at a time from the database is probably the best way to go, but then you'll have to modify the rest of the code to iterate over the list of N images and retrieve the data for each from the file system and return something like a list of the raw image data blobs.