You can download this code by clicking the button below.
This code is now available for download.
This code defines a Celery task that randomly selects one of the add, multiply, and divide functions to execute and returns the result. If the divisor is zero, a ValueError is raised.
Technology Stack : This code defines a Celery task that randomly selects one of the add, multiply, and divide functions to execute and returns the result. If the divisor is zero, a ValueError is raised.
Code Type : Celery task
Code Difficulty : Intermediate
from celery import Celery
from celery.utils.log import get_task_logger
import random
app = Celery('tasks', broker='pyamqp://guest@localhost//')
logger = get_task_logger(__name__)
def add(x, y):
return x + y
def multiply(x, y):
return x * y
def divide(x, y):
if y == 0:
raise ValueError("Cannot divide by zero")
return x / y
def generate_task():
tasks = [add, multiply, divide]
selected_task = random.choice(tasks)
args = (random.randint(1, 100), random.randint(1, 100))
return selected_task, args
@app.task
def execute_random_task():
task, args = generate_task()
try:
result = task(*args)
return result
except ValueError as e:
return str(e)
# JSON Explanation