celery-types

repository·main·Indexed 41 days ago

https://github.com/sbdchd/celery-types

Type stubs for Celery version 0.26.0 and its ecosystem, including related libraries such as kombu, amqp, django-celery-results, billiard, vine, and ephem, to improve type safety and developer experience.

Tokens
2.3K
Snippets
8
Records
13
Agent score
99%

What's inside celery-types

  1. Enable generic parameters via monkey patching

    main

    Because many Celery classes do not natively support subscripting (e.g., Task[int]), you must monkey patch the relevant classes to allow generic parameters to be provided for type hinting. You can select only the classes you intend to use from the list below.

    from celery import Celery, Signature
    from celery.app.task import Task
    from celery.contrib.abortable import AbortableAsyncResult, AbortableTask
    from celery.contrib.django.task import DjangoTask
    from celery.local import class_property
    from celery.result import AsyncResult
    from celery.utils.objects import FallbackContext
    
    classes = [
        Celery,
        Task,
        DjangoTask,
        AbortableTask,
        AsyncResult,
        AbortableAsyncResult,
        Signature,
        FallbackContext,
        class_property,
    ]
    
    for cls in classes:
        setattr(  # noqa: B010
            cls,
            "__class_getitem__",
            classmethod(lambda cls, *args, **kwargs: cls),
        )
  2. Celery CLI Command and Option Base Classes

    main

    Celery's CLI is built on top of click. The following classes define the base behavior for commands and options within the Celery ecosystem:

    • CeleryCommand: A subclass of click.Command that holds a reference to a Celery app instance (app: Celery | None).
    • CeleryDaemonCommand: A specialized CeleryCommand designed for daemonized processes.
    • CeleryOption: A subclass of click.Option used for Celery-specific command options.
    • DaemonOption: A specialized click.Option that includes a daemon_setting method for managing daemon configurations.
  3. Use MultiTool for multi-worker management

    main

    The MultiTool class is the primary interface for managing Celery clusters (multiple workers/nodes) via the command line. It extends TermLogger to provide terminal-based logging and status reporting.

    Key capabilities include:

    • Cluster Management: Starting, stopping, restarting, and killing clusters of nodes.
    • Command Execution: Running commands across multiple nodes via execute_from_commandline or call_command.
    • Lifecycle Hooks: Providing callbacks for node events such as on_node_start, on_node_down, and on_child_failure to customize how the tool reacts to worker state changes.
    • Terminal Output: Using methods like ok(), error(), info(), and note() to provide formatted feedback to the user.
    # Example conceptual usage of MultiTool
    from celery_stubs.bin.multi import MultiTool
    
    # Initialize the tool
    tool = MultiTool(cmd='multi')
    
    # Execute a command from a list of arguments
    # e.g., simulating: celery multi start worker1 worker2
    exit_code = tool.execute_from_commandline(['start', 'worker1', 'worker2'])
  4. Manage Celery cluster lifecycles with MultiTool

    main

    The MultiTool class provides high-level methods to control a _Cluster object (representing a group of Celery nodes):

    MethodDescription
    start(cluster)Starts the specified cluster of nodes.
    stop(cluster, sig, **kwargs)Sends a signal (sig) to the cluster to initiate shutdown.
    stopwait(cluster, sig, **kwargs)Sends a signal and waits for nodes to shut down (aliased as stop_verify).
    restart(cluster, sig, **kwargs)Restarts the cluster nodes using the provided signal.
    kill(cluster)Forcefully terminates the cluster.
    show(cluster)Displays the current status of the cluster.
    names(cluster)Lists the names of the nodes in the cluster.
  5. Configure TermLogger for terminal output

    main

    The TermLogger class (which MultiTool inherits) manages how the CLI communicates with the user. You can configure the terminal environment using setup_terminal to control verbosity, color, and output streams.

    Configuration Options for setup_terminal:

    • stdout: The output stream for standard messages.
    • stderr: The output stream for errors.
    • nosplash: Boolean to disable the splash text.
    • quiet: Boolean to suppress non-essential output.
    • verbose: Boolean to enable detailed output.
    • no_color: Boolean to disable colored terminal output.
    # Configuring terminal behavior
    logger.setup_terminal(
        stdout=None, 
        stderr=None, 
        quiet=False, 
        verbose=True, 
        no_color=False
    )
  6. Celery CLI Utility Functions

    main

    The following utility functions are available for handling CLI-related logic:

    • get_current_app(): Returns the current active Celery app instance.
    • pformat(object, ...): A highly configurable pretty-printer for Python objects, supporting indentation, width, depth, and dictionary sorting.
    • mlevel(level): Converts a log level (string or integer) into its integer representation.
    • maybe_iso8601(dt): Attempts to parse a datetime or string into a datetime object using ISO8601 format.
    • handle_preload_options(f): A decorator used to handle option preloading logic.
  7. Celery CLI Context and Output Utilities

    main

    The CLIContext object provides utilities for managing the CLI environment and formatting output. It is associated with a Celery app instance and includes methods for styled printing and data formatting.

    Key methods include:

    • echo(message, **kwargs): Prints a message.
    • error(message, **kwargs): Prints an error message.
    • secho(message, **kwargs): Prints a message with ANSI color/style.
    • pretty(n): Returns a formatted string representation of an object.
    • pretty_dict_ok_error(n): Formats a dictionary for success or error states.
    • pretty_list(n): Formats a list for display.
    • say_chat(direction, title, body, show_body): Formats a chat-like message block.
  8. Configure celery worker options

    main

    When running the worker command, you can use several flags to control its behavior. Key configuration options include:

    • --autoscale: Accepts a value that converts to a tuple of two integers (max_concurrency, min_concurrency) to manage worker process scaling.
    • --celery-beat: A boolean flag to enable/disable Celery Beat functionality.
    • --hostname: Sets the hostname for the worker.
    • --workers-pool: Specifies the pool type (using WorkersPool choices).
    • --fake-fork: (Represented by C_FAKEFORK) A string option for fork behavior.

    Additionally, the underlying detach mechanism allows for daemonization with options like --logfile, --pidfile, --uid, --gid, --umask, and --workdir.

    worker --autoscale 10,2 --hostname my-worker --workers-pool solo
  9. Celery CLI Parameter Types

    main

    The Celery CLI uses several specialized parameter types for parsing command-line arguments. When building or extending Celery commands, you can use these types to ensure correct validation and parsing of inputs.

    COMMA_SEPARATED_LIST: CommaSeparatedList
    LOG_LEVEL: LogLevel
    ISO8601: ISO8601DateTime
    ISO8601_OR_FLOAT: ISO8601DateTimeOrFloat
    JSON_ARRAY: JsonArray
    JSON_OBJECT: JsonObject