# Iteration and memcache for selected categorized random elements

The following code is a quick implementation since I only needed 3 random images sorted by category (a random eyes image, a random nose image and a random mouth image and then combine them):

    fileinfos = FileInfo.all().filter("category =", "eyes")
fileinfo = fileinfos[random.randint(0, fileinfos.count()-1)]
url = images.get_serving_url(str(fileinfo.blob.key()), size=420)
fileinfos = FileInfo.all().filter("category =", "nose")
fileinfo2 = fileinfos[random.randint(0, fileinfos.count()-1)]
url2 = images.get_serving_url(str(fileinfo2.blob.key()), size=420)
fileinfos = FileInfo.all().filter("category =", "mouth")
fileinfo3 = fileinfos[random.randint(0, fileinfos.count()-1)]
url3 = images.get_serving_url(str(fileinfo3.blob.key()), size=420)


This case is somewhat specific since the number of selection are fixed to 3. Surely iteration or a function to do this is preferred and memcache would also increase response time since there are not many files and the same file gets chosen sometimes then I'd like to use memcache and it seems memcache can cache the results from get_serving_url so I could cache the fileinfos or the results from get_serving_url. I know memcache is limited in memory.

    def get_memcached_serving_url(fileinfo):
memcache_key = "blob_%d" % fileinfo.blob.key()
data = memcache.get(memcache_key)
if data is not None:
return data


And I think I can't cache the blob itself and only the result from get_serving_url while it is the trip to the datastore that supposedly takes time.

Please tell me any thoughts or opinions about this quick prototyping how to get random elements while hoping to cache elements since the number of elements is still not very large (<100 elements and if the same is chosen twice then I'd like a fast and preferably cached response)

If you want you can have a look at the actual application here.

Regarding image caching, this seems relevant.

Secondly, DRY this code up, it'll make your code more maintainable:

fileinfos = FileInfo.all().filter("category =", "eyes")
fileinfo = fileinfos[random.randint(0, fileinfos.count()-1)]
url = images.get_serving_url(str(fileinfo.blob.key()), size=420)


Should have it's own function (forgive my py):

def get_random_image_url(category)
fileinfos = FileInfo.all().filter("category =", category)
fileinfo = fileinfos[random.randint(0, fileinfos.count()-1)]
return images.get_serving_url(str(fileinfo.blob.key()), size=420)

eyes_url = get_random_image_url("eyes")
nose_url = get_random_image_url("nose")
mouth_url = get_random_image_url("mouth")

• Thank you for the important help with structuring it to a function. Thank you also for the link with the important insight when not to use memcache. – Niklas Sep 2 '11 at 23:24