Do you think IIT Guwahati certified course can help you in your career?
No
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.
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.
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))
You can also try this code with Online Python Compiler
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:
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))
You can also try this code with Online Python Compiler
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))
You can also try this code with Online Python Compiler
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)
You can also try this code with Online Python Compiler
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
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