Server side global variable not working as expected

Here is a sample of the server side code:

import anvil.server

var = {‘a’:1, ‘b’:2}

@anvil.server.callable
def a():
global var
var[‘c’] = 3

@anvil.server.callable
def b():
print(var)

From client code, I call A first then B. Result:
{‘a’:1, ‘b’:2}

Since a() modifies var from the outer scope, I need global var. But since b() just references var, I should see the modified result no?

This isn’t quite how Server Calls work. Every time you make a server call, the Server module is loaded again.

There are two fixes for the problem

3 Likes

Perfect, thank you for the information!

I would like to add that:

  • Even with the persistent server, globals are not guaranteed to persist across calls. They will persist (maybe) most of the times, but any server can restart at any time, and your calls could be routed to different servers for load balancing or other reasons.
  • Sessions and cookies are good for small amounts of data. For larger amounts of data you can use a datatable and use the session as the key (and clean up the datatable with a nightly scheduled task).
2 Likes

Yes, which is why I like to think of them as a cache. You always need a fallback routine to fetch or regenerate the value, if it is not in the cache.

If the value needs a lifetime that is guaranteed to be longer, then it needs to go into some database table.

1 Like

Thank you all for the information. Very helpful and I have solved my issue.

Is the fact that server side globals are incompatible in Anvil documented someplace? Others my fall into this hole as well :wink:

The documentation was mentioned by @divyeshlakhotia, and covers these details.

In fact, it covers them better than I remember. Kudos to the Anvil crew for adding the important details!

1 Like