Get return value of background task

I clone this app, but nothing is printed thought there are two print statement. if task.is_completed() is added as well, but still doesn’t work.

https://anvil.works/build#clone:AWHJVR77QWY2V3R6%3D5WDDBEFKBYGUWLKT2P47BJXK

@anvil.server.background_task
def make_slow_request():
  response = anvil.http.request("https://httpstat.us/200?sleep=5000")  # An API that provides slow responses
  # Output some state from the task
  print(task.get_state()['false_positive_rate'])

  # Is the task complete yet?
  if task.is_completed():
    print(response)
    return "done"
    

  
@anvil.server.callable
def launch_slow_request_task():
  task = anvil.server.launch_background_task('make_slow_request')
  return task


1 Like

You can’t print to the console statement from within the background task itself, but you will find those print statements in the app logs.

here’s some more info in the docs:
https://anvil.works/docs/background-tasks/communicating-back#print-from-background-tasks

1 Like

Thanks, how about get the “done” value when the task is done?

Something like…

@anvil.server.callable
def launch_slow_request_task():
  task = anvil.server.launch_background_task('make_slow_request')
  return task

on the client you can do

self.task = anvil.server.call_s('launch_slow_request_task')

self.timer.interval = 1


def timer_tick(self, **event_args):
  with anvil.server.no_loading_indicator:
   if self.task.is_completed():
      print('done')
      self.timer.interval = 0
    

2 Likes

Really appreciate that.
I guess the document need to update your solution to make it clearer:
https://anvil.works/docs/background-tasks/communicating-back

def timer_tick(self, **event_args):
  with anvil.server.no_loading_indicator:
   if self.task.is_completed():
      alert(self.task.get_return_value()) #a bit modification
      self.timer.interval = 0

This tutorial has some pretty great examples of background tasks being used.

2 Likes