I have a client callable function to update the global variable in the server module using the “global” key-word. However, it doesn’t upload the global variable in the server code as I planned, why?
Such as:
in the server module I have:
x = 5
@anvil.server.callable
def update_glob():
global x
x = 6
print(x)
in the client module I have:
class Form1(Form1Template):
def __init__(self, **properties):
# Set Form properties and Data Bindings.
self.init_components(**properties)
anvil.server.call('update_glob')
# Any code you write here will run when the form opens.
However after I click the run button, the only output is 5, which is the unmodified x value
Your code isn’t indented, as Python requires, so it’s hard to tell what’s going on from your example. Try putting three backquotes (`) on their own line, before and after each code block. Then we can see where your classes and functions end.
If you move the print(x) call into function update_glob, I think you’ll see it working.
Currently, where the print is located, it executes once, immediately after update_glob is defined. It is not being executed at all later, when update_glob is called.
The problem is that the server code is reloaded every time you make a call to the server and all the globals are lost… unless you check the “keep server running” option, in which case the interpreter is not restarted at every call. But it still restarts once in a while, so you can’t rely on it.
Globals on the client side are reliable, because the interpreter starts when the app loads and they are kept until the browser is closed.