Based on suggested reviews for Function to lock a file using memcache, I have modified the code to
import os import shutil import memcache def addToCart(filename, username): ableToLock = memcache.add(filename, username) if ableToLock: # "ableToLock" can happen if the file is still present # or if it was already processed. if os.file.ispath(filename): # I have a lock and file exists. Think of Cart as a # JS Object from where you can pick items to "process". return "Added To Cart" else: # I have a lock but looks like file was processed already. # So removing the residual "key" created. memcache.delete(filename) return "Processed by another user." else: # "add" can also fail if remote server is down, # but now we are not handling that now. It will # block the user's ability to process anything. user = memcache.get(filename) if user and os.file.ispath(filename): # I try my best to show the user processing it. print "Being processed by %s" % user else: # But lost the race to find that. print "Processed by another user." def process(source): shutil.move(source, destination) filename = os.path.basename(source) memcache.delete(filename)
process is not considered valid as it can only be done from user's Cart and by that user. If the logic is correct, Cart will only have valid files at any point of time and no two Carts would be having the same file ever. If a request from Cart comes to process a filename and it doesn't exist in the file-system then it is considered flawed.
Are there any race conditions or logical flaws that still exists?