Toady I was working on my API for The Italian Bay and realized that, other than cleaning untidy and sloppy code, I still hadn’t implemented any sort of cache. Thanks to Python’s excellent decorator feature and to the excellent community on IRC this is what I have come up with.
What do I need to do to cache my calls?
All you need to do is to add one very simple line of code at the top of every function: @CacheControlled . From that moment on you can go to sleep knowing that your server will serve request so much faster than before and your clients will be so much more satisfied (you will magically become the king of servers).
Show me that code!
Easy fella, heres my code directly on Github. If you believe i’ve done something catastrophic of just want to contribute to my projects please fork me and I will be very happy.
def CacheControlled(function): """this function should be called by each API call, it's use is to return cached data or cache when possible""" def wrapper(*args, **kwargs): unique_string = repr((args, kwargs)) # check if in cache, if it is just return the result cached_result = memcache.get(unique_string, function.__name__) if cached_result is not None: return cached_result # Let's run the function and cache itresult = function(*args, **kwargs) r = memcache.add(unique_string, result, 3600, 0, function.__name__) return result return wrapper
And all you need to do is
@CacheControlled def my_function(a,b): #function body
It's incredible how 10 magic lines in Python can change the whole browsing experience. The Italian Bay needs to do lots of scraping in order to get the results the user wants and this can take some time, when the page is cached for an hour the whole browsing experience is incredibly more faster. The decorator in a first moment checks if the unique function has been cached previously, if it has the cached result will be return. If has not been cached it will execute the function with it's parameters and, before returning the results, will cache it with a unique key.
In conclusion
I'm sure this is not perfect, but it surely can be useful to anyone who needs a fast and efficient way to speed up his web application. If you have any hints on how this can be improved (I am sure there are billions of ways) please let me know, and we can all be contributors to the best cache decorator written by the community.
Dan
Related posts:



