0

I'm trying to cache and retrieve an object using the cache.set() and cache.get() methods, but I'm having some trouble getting it to work properly. I use the .set() method to cache an object (obj1) that has another object (obj2) as its attribute. After retrieving the cached object (obj1) using cache.get(), I am not able to access the attributes of obj2. I'm getting an AttributeError: 'CustomDataFrame' object has no attribute '_var1'.

Expected behavior:

Before caching, var1: Remember me
After caching, var1: Remember me

Actual behavior:

Before caching, var1: Remember me
AttributeError: 'CustomDataFrame' object has no attribute 'var1'.

Minimal reproducible example:

from flask import Flask
from flask_caching import Cache
import pandas as pd

app = Flask(__name__)

# Configure Flask-Cache
app.config["CACHE_TYPE"] = "filesystem"
app.config["CACHE_DIR"] = "/tmp"
app.config["CACHE_DEFAULT_TIMEOUT"] = 600

cache = Cache(app)


class CustomDataFrame(pd.DataFrame):
    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self.var1 = None

    def custom_method(self, arg1, arg2):
        # perform some custom operation
        pass
        

class DataFrameManager():
    def __init__(self, df: CustomDataFrame):
        self.df = df  

    def custom_method(self, arg1, arg2):
        # perform some custom operation
        pass


# Set up a route that uses caching
@app.route("/")
def set_and_get_route():
    # Create custom object
    data = {'name': ['Alice', 'Bob'], 'age': [24, 32]}
    df = CustomDataFrame(data)
    df.var1 = "remember me"
    df_manager = DataFrameManager(df)

    # Use .set() to store a value in the cache
    print(f"Before caching, var1: {df_manager.df.var1}")
    cache.set("df_manager", df_manager)

    # Use .get() to retrieve a value from the cache
    retrieved_df_manager = cache.get("df_manager")
    print(f"After caching, var1: {retrieved_df_manager.df.var1}")


    return "dummy"

if __name__ == "__main__":
    app.run()
Boe
  • 17
  • 4

0 Answers0