Realtime Usecase Of Python Decorator Using Custom File Based Caching.
Decorator: decorator is a kind of design pattern which enables you to add and modify of your functions or methods without changing their existing source code.
In python you can apply decorator to your existing functions or method by using @ symbol decorator name.
In python you can create decorator by two way class based and function based it upto you.
Step 1. Create a class for File Storage which set and get data in the form of json in file.
import json
class FileStorage:
def __init__(self, file):
"""
parameters
:file str -> file name must be json format with .json ext.
"""
self.file = file
def get(self):
try:
with open(self.file, "r") as file:
return json.load(file)
except FileNotFoundError:
return {}
def set(self, data):
with open(self.file, "w") as file:
json.dump(data, file)
Step 2 : Create function based decorator that will cache your function data.
def file_cache(key, file):
"""
parameters
:key str -> unique key to save data
:file str -> json format file to store data
"""
def inner(fun):
def wrapper(*args, **kwargs):
file_obj = FileStorage(file)
cache_dict = file_obj.get()
if key in cache_dict:
return cache_dict[key]
else:
result = fun(*args, **kwargs)
cache_dict[key] = result
file_obj.set(cache_dict)
return result
return wrapper
return inner
Create another decorator i.e class based will check the how much time taken by the function.
import time
class timer:
def __init__(self, fun):
self.fun = fun
def __call__(self, *args, **kwargs):
start = time.time()
data = self.fun(*args, **kwargs)
end = time.time()
total_time = end - start
print(f"Total time taken: {total_time}")
return data
Step 3. Our existing function
import requests
API_URL = “https://jsonplaceholder.typicode.com/posts”
@timer
@file_cache(key = "post_data_101", file="file.json")
def data_list(api_url):
resp = requests.get(api_url)
json = resp.json()
return json
data_list(API_URL)
This is a function that make a request to an api and fetch data from api and it is taking sometime after apply decorator it will cache the data and next time it will return data from our cache_dict and it will not make next request to api.
It will make your function performance boost 10x .
Conclusion: You can use your custom redis cache and another cache machanism in place of file cache.
Make sure your file size should be limited.
Keep learning keep growing!
Comments