Generalize Form Caching Logic

What I’m trying to do:
Boil down some form caching logic to be more generalizable. See this post for more context if you’re interested on where I’m coming from.

Here is the more specialized version of the caching logic that only works with one form.

  def link_home_click(self, **event_args):
    self.home_form = self.home_form or Home()
    self.content_panel.clear()
    self.content_panel.add_component(self.home_form)

What I’ve tried and what’s not working:
I’m trying to use higher order functions, by passing in the constructor for a given form to some caching logic, but it doesn’t work… not really sure why… anyway, here’s the trouble code.

Code Sample:

  def try_get_cached_form(self, form_property, form_constructor):
    form_property = form_property or form_constructor()
    self.content_panel.clear()
    self.content_panel.add_component(form_property)

Calling Code:

  def link_calendar_click(self, **event_args):
    self.try_get_cached_form(self.calendar_form, Calendar)

Clone link:
https://anvil.works/build#clone:2YTMQUCIDGNA2IRB=MDMPBUZGUV37OUW2I35QNITS

Any help is appreciated :slight_smile:

1 Like

I would use a dictionary to cache all the forms and use the form class itself as the dictionary key:

  def __init__(self, [...]):
    [...]
    self.form_cache = {}

  def link_home_click(self, **event_args):
    self.try_get_cached_form(Home)

  def link_calendar_click(self, **event_args):
    self.try_get_cached_form(Calendar)

  def try_get_cached_form(self, form_constructor):
    form = self.form_cache.get(form_constructor)
    if not form:
        print(f'adding {form_constructor} to the cache')
        form = self.form_cache[form_constructor] = form_constructor()
    self.content_panel.clear()
    self.content_panel.add_component(form)

As a side note the hash routing module comes with form caching that can be disabled when you don’t want to use stale cache. It will not be as flexible as a custom made cache, but for simple cases that could be enough.

You can find the hash routing module here, and it’s also included (without documentation, but with full functionality) in Anvil Extras.

3 Likes

I am not sure if this is what you actually meant by form caching but I have implemented forms which retain their state many times in my app.

I’ll just create a new instance on the form upon init

from Form_to_be_cached import Form_to_be_cached

self.cached_form=Form_to_be_cached()


Now our self.cached_form is available everywhere inside the current form so you can just add or remove it from components as you see fit.

However, if you have a code running upon the ‘show’ event of the cached form, it will be called again if you change the visible property of the cached form.

2 Likes