Anvil.server.context.type in background tasks

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