Missing session data

What I’m trying to do:
I am trying to access anvil.server.session data, but it is empty.

What I’ve tried and what’s not working:
I set some session values in function A. I then call function B from within function A and the session variables are not set.

Code Sample:

# this is a very cut down snippet of code.
@anvil.server.callable
def authenticate_user(**kwargs):
  username = kwargs.get("username", None)
  password = kwargs.get("password", None)
  res = anvil.server.call("uplink_login", username=username, password=password)
  if res.status == 200:
    anvil.server.session['username'] = username
    anvil.server.session['email'] = res.data[0]['email']
    anvil.server.session['role_name'] = res.data[0]['role_name']
    debug.print(anvil.server.session) # <---THEY ARE SET HERE
    return Response(200, [anvil.server.call("fetch_safe_data")], "")
  else:
    return Response(401, [], "login failed")
    
@anvil.server.callable
def fetch_safe_data():
  debug.print(anvil.server.session) # <--- THEY ARE NOT SET HERE
  ret = {
    "username": anvil.server.session['username'],
    "role_name": anvil.server.session['role_name'],
    "email": anvil.server.session['email']
  }
  return ret

Is this expected behaviour? If so, why? Or am I doing something dazzlingly stupid?

EDIT - If I “un-decorate” fetch_safe_data() so it is a “normal” function, the problem goes away. So it’s something to do with the decorated function not having the session data yet. So again - is this expected behaviour?

That makes sense to me, based on my understanding of how sessions normally work. The server sends the client a session id that then gets sent back to the server with each call.

By using anvil.server.call("fetch_safe_data") instead of fetch_safe_data() you’re making a call to another server. Apparently that session id isn’t getting forwarded along, so that next server instance thinks it’s a new session.

That’s all conjecture, of course.

1 Like

I was kinda thinking broadly the same thing.

As it happens it’s sort of moot now, as I incorrectly thought that I couldn’t call a decorated function without using anvil.server.call, but actually you can so all is well. Would be good to have our assumptions confirmed though.

Also, it forced me to rethink a poorly designed set of function interactions which can only be a good thing :slight_smile:

1 Like