What I’m trying to do:
I have a global variable defined in my main module containing user info. I would like to be able to use this variable outside of the module in my actual forms.
My startup Module, MainModule, is set up like so:
def main():
global user
# check if a user is logged in
user_logged_in = anvil.server.call("check_user_login_status")
if user_logged_in:
user = user_logged_in
open_form("MainRouter")
else:
# Redirect user to login template:
user = None
open_form("FormLandingPage")
if __name__ == "__main__":
main()
What I’ve tried and what’s not working:
I would like to be able to use the global variable ‘user’ in my MainRouter form,
but when I import MainModule ( from … import MainModule) into MainRouter, I get the following error:
AttributeError: module 'MyApp.MainModule' has no attribute 'user'
** Some other potentially relavent details**
MainModule is my startup form
MainRouter uses HashRouting and has the decorator ‘@routing.main_router’
Please let me know if there are any other details I can supply. Based on what I’ve read on other forms (and in anvil-extras docs here: Routing — Anvil Extras documentation) it seems like what I am trying to do should work… Thanks!
Perhaps all you need is to add user = None outside of the main function, so the variable user is defined in the module rather than used as a global reference inside a function.
(wrt the image, MainModule line 34 is open_form(“MainRouter”))
I have tried setting user = None outside of the main function, this prevents the error but causes the global var user to have the value None in all forms
aka:
# In MainRouter
from .. import MainModule
print(MainModule.user) # prints "None"
I wouldn’t rely on global variables that only exist in your startup module.
That’s because your startup module is initially executed with __name__"__main__" but when it is subsequently imported to another form it is re-executed with __name__"MainModule". If you print __name__ in the module scope you’ll see this gets executed twice.
Better to put user into a Globals module and import the Globals module into both the startup module and the main form. Then access it like Globals.user