Task
For typing concerns, you may want to import the class Task
in your code.
from abstra.tasks import Task
Useful methods
There are some useful methods to be called on instances of this class. As an example, let's suppose that we are dealing with the task created on the following code:
send_task("approved", {
"name": "Michael Scott",
"company": "Dunder Mifflin",
})
For the following, let us suppose we retrieved this task in a variable called task
.
Get data from the task
Payload data
You can access directly the value of a key in the payload by using task.key
.
print(task["name"]) # Michael Scott
print(task["company"]) # Dunder Mifflin
Get the full payload at once
The function task.get_payload()
will return the payload of the task:
task.get_payload()
'''
Returns:
{
"name": "Michael Scott",
"company": "Dunder Mifflin",
}
'''
Task native data
You can also retrieve the task id and type with task.id
and task.type
:
print(task.id) # 23786870-5603-4765-af7c-bcd959cdff2f
print(task.type) # approved
Complete a task
A task has three possible statuses: pending, locked and completed. When a task is created and sent to the next stages, it is sent as a pending task. When a task is retrieved on another stage, it is set as locked, so no other parallel execution of that stage can cause trouble with it. Finally, it is up to the user call task.complete()
to set the task as completed. Otherwise, it will be set to pending again at the end of the execution of the stage.
from abstra.tasks import get_tasks
pending_tasks = get_tasks()
for task in pending_tasks
if some_condition == True:
task.complete()
An alternative to task.complete()
is to use the Python context manager, that will handle the task lifecycle by itself:
from abstra.tasks import get_trigger_task
task = get_trigger_task()
with task:
# do anything
At the end of the with task
block, the task will be completed if no exceptions were raised or set back to pending, otherwise.