Random Arithmetic Operation Celery Task

  • Share this:

Code introduction


This code defines a Celery task that randomly selects an arithmetic operation (addition, multiplication, division, or subtraction) and performs it on two randomly generated numbers.


Technology Stack : Celery, Python

Code Type : Celery task

Code Difficulty : Intermediate


                
                    
from celery import Celery
from celery.utils.log import get_task_logger
import random
import json

app = Celery('tasks', broker='pyamqp://guest@localhost//')
logger = get_task_logger(__name__)

def random_task():
    # This function is a random Celery task that performs a simple calculation
    def add(x, y):
        return x + y

    # Select a random operation to perform
    operations = ['add', 'multiply', 'divide', 'subtract']
    operation = random.choice(operations)

    # Randomly select two numbers for the operation
    num1 = random.randint(1, 100)
    num2 = random.randint(1, 100)

    # Perform the operation
    if operation == 'add':
        result = add(num1, num2)
    elif operation == 'multiply':
        result = num1 * num2
    elif operation == 'divide':
        if num2 != 0:
            result = num1 / num2
        else:
            result = "Division by zero is not allowed."
    elif operation == 'subtract':
        result = num1 - num2

    return result

# Code Explanation                
              
Tags: