Code360 powered by Coding Ninjas X Naukri.com. Code360 powered by Coding Ninjas X Naukri.com
Table of contents
1.
Introduction
2.
What is cache
3.
Cache in web2py
3.1.
🔖Implementation of cache.disk
3.2.
🔖Implementation of cache.ram 
3.3.
🔖Implementation time.ctime() function to both RAM and disk:
3.4.
🔖Caching in RAM the result of the controller function (but not the view)
3.5.
🔖Caching the result of the controller function on disk (but not the view)
3.6.
🔖 Caching the output of the controller function in RAM (including the rendered view) 
4.
Cache.action in web2py
5.
Cache.action Parameter 📝  
6.
Frequently Asked Question
6.1.
What is cache?
6.2.
Define Cache in web2py?
6.3.
Define Cache.action in web2py?
6.4.
What is the use of the cache_model parameter in the Cache.action?
6.5.
What is the use of the quick parameter in the Cache.action?
7.
Conclusion
Last Updated: Mar 27, 2024
Medium

Cache and Cache.action in web2py

Author Alok Pandey
0 upvote
Master Python: Predicting weather forecasts
Speaker
Ashwin Goyal
Product Manager @

Introduction

Have you ever get surprised to see the website is opening some of the content even if you are not connected to the internet? This is due to the cache mechanism of the browser. 

Cache and Cache.action in web2py

In this article, we will try to understand what is Cache and Cache.action in web2py. We also see the code implementation for a better understanding of the topic.

What is cache

A cache is a piece of software or hardware that is used in a computing system to temporarily store something, often data. In order to give software or hardware faster access to data or files, a cache is a temporary data storage area where copies of frequently visited data or files are kept. A cache is a tool used by computers, mobile devices, web browsers, and other programs to expedite data retrieval.

Get the tech career you deserve, faster!
Connect with our expert counsellors to understand how to hack your way to success
User rating 4.7/5
1:1 doubt support
95% placement record
Akash Pal
Senior Software Engineer
326% Hike After Job Bootcamp
Himanshu Gusain
Programmer Analyst
32 LPA After Job Bootcamp
After Job
Bootcamp

Cache in web2py

Cache in web2py

A Cache is a global object also available in the web2py execution environment. The cache is callable in programs. That is why the cache is used as a decorator for caching actions and views. Cache has two attributes:

🔖Implementation of cache.disk

Caches the time.ctime() function on disk:

def disk_cache():
    import time
    tim = cache.disk('time', lambda: time.ctime(), time_expire=10)
    return dict(time=tim, link=A('click me', _href=request.url))

The output of lambda: time.ctime() is cached on disk for 10 seconds.

🔖Implementation of cache.ram 

Caches the time.ctime() function in RAM:

def ram_cache():
    import time
    tim = cache.ram('time', , time_expire=10)
    return dict(time=tim, link=A('click lambda: time.ctime()me', _href=request.url))

The output of lambda: time.ctime() is cached in RAM for 10 seconds. The string 'time' is used as the cache key.
 The second argument to cache.disk and cache.ram must be a function or callable object. You may just return it via a lambda function if you wish to cache an existing object rather than the result of a function:

cache.ram('anyobject', lambda: anyobject, time_expire=60*60*24)

🔖Implementation time.ctime() function to both RAM and disk:

The following function caches the time.ctime() function to both RAM and disk:

def ram_and_disk_cache():
    import time
    tim = cache.ram('time', lambda: cache.disk('time', lambda: time.ctime(), time_expire=10), time_expire=10)
    return dict(time=tim, link=A('click me', _href=request.url))

The output of the function lambda: time.ctime() is cached on disk and then in RAM for 10 seconds. If RAM is not available, web2py first checks on disc. If the cache is not in RAM or on disk, lambda: time.ctime() is executed and the cache is updated. This method is useful in a multiprocessor environment. It's not necessary for the two timings to same.

🔖Caching in RAM the result of the controller function (but not the view)

Let’s see the implementation of Caching in RAM and the output of the controller function on the disk (but not the view)

@cache(request.env.path_info, time_expire=10, cache_model=cache.ram)
def ram_controller_cache():
    import time
    tim = time.ctime()
    return dict(time=tim, link=A('click me', _href=request.url))

The output of the function ram_controller_cache returns a dictionary that is cached in RAM for 10 seconds. Point to keep in mind that a database select's output cannot be cached without first being serialized. Caching the database selected directly using the select method's cache parameter is a superior approach.

🔖Caching the result of the controller function on disk (but not the view)

Let’s see the implementation of Caching in disk the output of the controller function on the disk (but not the view)

@cache(request.env.path_info, time_expire=10, cache_model=cache.disk)
def disk_controller_cache():
    import time
    tim = time.ctime()
    return dict(time=tim, link=A('click to reload', _href=request.url))

The above function disk_controller_cache returns a dictionary that is cached in the disk for 10 Seconds. Remember that web2py cannot cache a dictionary that contains un-pickleable objects.
Caching the view is another option. Rendering the view within the controller function is the secret to getting the controller to return a string. This is done by returning a response. render(dic) where dic is the dictionary we intended to pass to the view.

🔖 Caching the output of the controller function in RAM (including the rendered view) 

Let’s see the implementation of Caching the output of the controller function on the RAM (including the rendered view)

@cache(request.env.path_info, time_expire=0, cache_model=cache.ram)
def cache_controller_and_view():
    import time
    tim= time.ctime()
    dic = dict(time=tim, link=A('click to reload', _href=request.url))
    return response.render(dic)

Here response.render(dic) returns the rendered view as a string, which is now cached for 10 seconds. This method is the best and fastest way of caching.

Cache.action in web2py

Cache.action in web2py

The default assumption of Web2py is that the returned content won't be cached, which minimizes the drawbacks of inappropriate client-side caching of the page.

For example, when we apply to cache in a dynamic website, it fails because the data has been modified. To handle this problem, web2py  introduced a decorator Cache.action.cache.action can be used for setting smart cache headers and to cache the results accordingly.

Cache.action was developed so that users wouldn't have to write a tonne of boilerplate code to solve issues with caching. To allow the browser to cache the output, it will by default utilize smart cache headers. If you supply a cache model to it, it will also choose the optimal key automatically, allowing various versions of the same page to be saved and retrieved in the appropriate ways.

Cache.action Parameter 📝  

Cache.action takes certain parameters which a user has to provide. There is some default value associated with these parameters so let's see what all parameters are cache.action takes and what are their default values.

cache_model: by default, it is None. 
The @cache.action will only change the default headers to let the browser cache the data if you pass, e.g., cache.ram. The output will be stored in the cache also.

time_expire: this parameter takes the time to expire the process. By default, it is 300 seconds

prefix: if the user wants to prefix the auto-generated key (useful for clearing it later with, e.g., cache.ram.clear(prefix*))

session: if the user wants to consider the session, it defaults to False 

vars: if the user wants to consider URL vars, it defaults to True

lang: if the user wants to consider the language, it defaults to True

user_agent: if the user wants to consider the user agent, it defaults to False

public: if the user wants the same page for all the users that will ever access it, it defaults to True

valid_statuses: defaults to None. 

quick: defaults to None, but a user can pass a list of initials to set a particular feature:

Vars, User_agent, Session, Lang, Public e.g. 
@cache.action(time_expire=300, cache_model=cache.ram, quick='SVP')  is also written as
@cache.action(time_expire=300, cache_model=cache.ram, session=True, vars=True, public=True)

Frequently Asked Question

What is cache?

A cache is a piece of software or hardware that is used in a computing system to temporarily store something, often data. In order to give software or hardware faster access to data or files, a cache is a temporary data storage area where copies of frequently visited data or files are kept.

Define Cache in web2py?

A Cache is a global object also available in the web2py execution environment. The cache is callable in programs. That is why the cache is used as a decorator for caching actions and views.

Define Cache.action in web2py?

Cache.action was developed so that users wouldn't have to write a tonne of boilerplate code to solve issues with caching. To allow the browser to cache the output, it will by default utilize smart cache headers.

What is the use of the cache_model parameter in the Cache.action?

 The @cache.action takes the default value as none and will only change the default headers to let the browser cache the data if you pass, e.g., cache.ram, the output will be stored in the cache also.

What is the use of the quick parameter in the Cache.action?

The default value of the parameter is None, but a user can pass a list of initials to set a particular feature: Vars, User_agent, Session, Lang, Public.

Conclusion

In this article, we have extensively discussed Cache and Cache.action in web2py. We have discussed what Cache is and how we can implement it in web2py and if you would like to learn more, check out our articles on

Refer to our guided paths on Coding Ninjas Studio to learn more about DSA, Competitive Programming, JavaScript, System Design, etc. 

Enroll in our courses and refer to the mock test and problems available.

Take a look at the interview experiences and interview bundle for placement preparations.

Conclusion Image

Do upvote our blog to help other ninjas grow. 

Happy Coding!

Previous article
Sessions in web2py
Next article
URLs in web2py
Live masterclass