Skip to content

support for callable unique_on taking args, kwargs #52

Open
@rooterkyberian

Description

@rooterkyberian

This is useful if you have a task which takes a complex object, but in fact uniqueness is only done based on single field of it, such as tasks taking User, but uniqueness check only needs user.id.

Of course you could argue, you shouldn't have such celery tasks with such complex object as params, but I think it should be left to the user to decide if is right for them or not.

At the same time it seems very easy to implement - for now I'm using custom subclass:

class UniqueFunctionSingleton(celery_singleton.Singleton):
    def generate_lock(self, task_name, task_args=None, task_kwargs=None):
        unique_on = self.unique_on
        task_args = task_args or []
        task_kwargs = task_kwargs or {}
        if callable(unique_on):
            unique_args = unique_on(*task_args, **task_kwargs)
            unique_kwargs = None
        else:
            if unique_on:
                if isinstance(unique_on, str):
                    unique_on = [unique_on]
                sig = inspect.signature(self.run)
                bound = sig.bind(*task_args, **task_kwargs).arguments

                unique_args = []
                unique_kwargs = {key: bound[key] for key in unique_on}
            else:
                unique_args = task_args
                unique_kwargs = task_kwargs
        return util.generate_lock(
            task_name,
            unique_args,
            unique_kwargs,
            key_prefix=self.singleton_config.key_prefix,
        )

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions