Enable Dark Mode!
how-to-apply-cache-on-pdf-reports.jpg
By: Swathy KS

How to Apply Cache on PDF Reports?

Technical

In software development, performance is crucial. Whether it's a web application responding to user requests or a backend system processing large volumes of data, the speed at which operations are performed can make a significant difference in user experience and operational efficiency. One powerful tool in the developer's arsenal for optimizing performance is cache.

Introducing the concept of applying caching to PDF reports using cache tools opens up avenues for optimizing efficiency and performance in document generation processes. By strategically caching previously generated reports, redundant computations are minimized, leading to quicker access and reduced strain on system resources. This introduction delves into the benefits and implementation strategies of leveraging cache tools to enhance the generation and retrieval of PDF reports.

How to configure cache tools?

Cache tools package is a Python library offering caching utilities like in-memory and disk caching, memoization, and cache management. It facilitates efficient storage and retrieval of frequently accessed data, reducing database load and improving application responsiveness. With flexible configuration options, Cache tools streamline caching implementation across various Python projects.

To install the Cache tools package in Python, you can use pip, the Python package installer. Simply open your terminal or command prompt and run:

pip install cachetools

Import cache-tools into your file and initialize the cache as follows.

import cachetools
cache = cachetools.TTLCache(maxsize=100, ttl=120)

* cache-tools: This is a Python library providing various cache implementations.

* TTLCache: This particular type of cache is a Time-To-Live (TTL) cache, where entries have a limited lifespan.

* maxsize=100: This sets the maximum number of items that the cache can hold. In this case, it's set to 100, meaning the cache can store up to 100 key-value pairs.

* ttl=120: This sets the time-to-live for each item in the cache in seconds. After 120 seconds (2 minutes) since an item was added or last accessed, it will expire and be removed from the cache.

How to apply TTLCache on PDF reports?

TTLCache on PDF reports in Odoo serves to store generated reports temporarily based on a specified time-to-live (TTL), reducing computation time by retrieving pre-generated reports within the TTL window.

First of all, we need to create a cache key for uniquely identifying the content of the pdf

cache_key = f"{bodies}"

Here I am using bodies as a cache key for uniquely identifying content.

Get data from the cache

If the data already exists in the cache, then get the data from the cache as follows.

cache_result = cache.get(cache_key)

If the data is present in the cache then return this cache result.

Set data on the cache

If the data is not present in the cache, then store it in the cache as a key-value pair.

cache[cache_key] = result 

result - Working the existing function and that content is stored in cache.

Here is the full code of how can apply caching in pdf reports using cache tools

# -*- coding: utf-8 -*-
from odoo import api, models
from odoo.sql_db import _logger
import cachetools
cache = cachetools.TTLCache(maxsize=100, ttl=120)



class PdfContent(models.Model):
    _inherit = 'ir.actions.report'

    @api.model
    def _run_wkhtmltopdf(
            self,
            bodies,
            report_ref=False,
            header=None,
            footer=None,
            landscape=False,
            specific_paperformat_args=None,
            set_viewport_size=False):
        cache_result = False
        cache_key = f"{bodies}"
        try:
            cache_result = cache.get(cache_key)
        except Exception as e:
            _logger.error(
                "Failed getting key from cache %s" % cache_key)
        if cache_result:
            return cache_result
        else:
            result = super()._run_wkhtmltopdf(bodies,
                                              report_ref=report_ref,
                                              header=header,
                                              footer=footer,
                                              landscape=landscape,
                                              specific_paperformat_args=specific_paperformat_args,
                                              set_viewport_size=set_viewport_size)
            cache[cache_key] = result
            return result

In conclusion, implementing TTLCache on PDF reports in Odoo offers a strategic solution to optimize report generation. By storing pre-generated reports temporarily, based on a specified time-to-live (TTL), it efficiently reduces computation time and enhances overall system performance, ensuring the timely delivery of accurate reports to users.

To read more about How to Create a PDF Report in Odoo 17?, refer to our blog How to Create a PDF Report in Odoo 17.


If you need any assistance in odoo, we are online, please chat with us.



0
Comments



Leave a comment

 


whatsapp_icon
location

Calicut

Cybrosys Technologies Pvt. Ltd.
Neospace, Kinfra Techno Park
Kakkancherry, Calicut
Kerala, India - 673635

location

Kochi

Cybrosys Technologies Pvt. Ltd.
1st Floor, Thapasya Building,
Infopark, Kakkanad,
Kochi, India - 682030.

location

Bangalore

Cybrosys Techno Solutions
The Estate, 8th Floor,
Dickenson Road,
Bangalore, India - 560042

Send Us A Message