Anvil.server.context.type in background tasks

I am debugging a background task by running it as a function from the server console. The function crashes when it tries to update its task status, so I have done this little change:

# old version
    anvil.server.task_state['progress'] = 'Doing something...'

# new version
    update_status('Doing something...')

def update_status(text):
    if anvil.server.context.type == 'background_task':
        anvil.server.task_state['progress'] = text
    elif anvil.server.context.type == 'server_module':
        print(text)
    else:
        raise Exception(f'Unexpected context type: {anvil.server.context.type}')

I thought this would print to console when running from console and would update the task status when running as background task, but it always prints, and I end up with task_state['progress'] never set and with all the info printed to the background task session log.

According to the documentation, when running in a background task it should be anvil.server.context.type == 'background_task', but it looks like it is always anvil.server.context.type == 'server_module'.

What am I missing?

I need to look a little deeper, I missed the .client part :frowning: .

This is what I get in a background task and from the console:

# on the server console
print(anvil.server.context)
<CallContext:{'type': 'server_module', 'client': <ClientInfo:{'type': None, 'ip': None, 'location': None}>, 'remote_caller': <StackFrame:{'type': None, 'is_trusted': False}>, 'background_task_id': None}>

# on a background task
print(anvil.server.context)
<CallContext:{'type': 'server_module', 'client': <ClientInfo:{'type': 'background_task', 'ip': None, 'location': None}>, 'remote_caller': <StackFrame:{'type': None, 'is_trusted': False}>, 'background_task_id': 'ghpyipzhbannqdi4uadazgweyhznxpcb242ihlm3'}>

The new code:

def update_status(text):
    if anvil.server.context.client.type == 'background_task':
        anvil.server.task_state['progress'] = text
    elif anvil.server.context.client.type is None:
        print(text)
    else:
        raise Exception(f'Unexpected context type: {anvil.server.context.client.type}')
1 Like