Using Globals to Limit Server Calls

I can’t find the original post, but at one point someone had put up a sample client side caching module that performed server calls only once for the items supported by the cache. Here’s a minimal version of it:

import anvil.server

def __dir__():
    return ['foo', 'bar', 'abc']
parameters = {}

def __getattr__(name):
  try:
    return parameters[name]
  except KeyError:
    try:
      value = anvil.server.call_s('get_' + name)
      parameters[name] = value
      return value
    except anvil.server.NoServerFunctionError:
      raise NameError(f"name '{name}' is not defined")  

In this you’d have a server function for each piece of data you want to cache, e.g. for the above you’d have server calls get_foo, get_bar, get_abc.

You’d import Cache into your client forms and use it like this to get the contents of the cache:

Cache.foo

The first time you get foo it gets it from the server, after that it gets the cached value. Useful for values that don’t change during a session.

1 Like