Cache variable in server code

Hello everyone!
This is my second post. I’m been working on anvil for like one week and there are a few things that i can’t find in docs or in the forum.

Currently i have an application that call an api when it start. I want to cache the response so when the same user (or other) use the app, the time will be fast.
I tried:

response = None

@anvil.server.callable
def getData():

  url = "api/my_url"

  global response
  if response:
    return response
  else:
    response = anvil.http.request(url, json=True)
    return response

The code above does not work. It seems to call the api everytime.
Also tried with session storage but it’s not what i want. ( in a extreme case it would work)

I want a way to store the api response in my server code.

Thank you all!

I think this might be the link in the docs that should explain the behaviour you’re experiencing

Anvil Docs | Server Code

Persistent server modules is the search term here.

Here’s a linked post that might also answer the question.

2 Likes

In cases such as these I tend to stuff the data (the json in your case) in a data table.

1 Like