Users.get_user() returns None in freshly launched background tasks

Hi @krasen,

Thanks for the clone link - that’s really helped us narrow it down!

It looks like your app was relying on a bug in Anvil’s Background Tasks implementation, which has now been fixed. In this post, I’ll explain why, and how to update your app so it works again:

When you launch a Background Task, it launches in a separate session (as described in the docs), which means it has a separate anvil.server.session_state, and a separate idea of whether there is a user logged in. In the app you’ve shared, you’re logging in as the admin user and then launching the call_inner_task_background background task. The call_inner_task_background function is running in a completely new session that knows nothing about the user you’ve just logged in!

The fix is to log the user in inside the background task. In your case, it’s always the same user, so it’s a simple change. If you wanted to tell the background task which user to log in as, you could pass the row from the Users table into the task, and use anvil.users.force_login() to log yourself in.

In fact, your app doesn’t need to use App Secrets to store the email and password of the admin user – you can just do:

superuser = app_tables.users.get(email="superuser@yourapp.com")
anvil.users.force_login(superuser)

So, why was this working before? In earlier versions of the Anvil platform, there was a bug that in some circumstances caused “leakage” of information (including logged-in user status) from the “launching” session into the “launchee” session of the background task. We have recently released an update that, among other things, fixes this bug! If your app was working before, it looks like your app had tickled this bug, and was relying on its behaviour.

I’m sorry about the unpleasant surprise, but the previous behaviour was buggy and unreliable, so we can’t sensibly change it back. We try to avoid making updates that break code that worked on previous versions; this is one of the rare exceptions. The best way forward is to update your app as described above.

I have moved this post out of the Bug Reports section, as it’s not exactly a bug in Anvil – or at least, it isn’t any more!

4 Likes