Wrapper to validate arguments and serialize return values using Pydantic.
(
app: "Celery",
task_fun: typing.Callable[..., typing.Any],
task_name: str,
strict: bool = True,
context: typing.Optional[typing.Dict[str, typing.Any]] = None,
dump_kwargs: typing.Optional[typing.Dict[str, typing.Any]] = None
)
| 167 | |
| 168 | |
| 169 | def pydantic_wrapper( |
| 170 | app: "Celery", |
| 171 | task_fun: typing.Callable[..., typing.Any], |
| 172 | task_name: str, |
| 173 | strict: bool = True, |
| 174 | context: typing.Optional[typing.Dict[str, typing.Any]] = None, |
| 175 | dump_kwargs: typing.Optional[typing.Dict[str, typing.Any]] = None |
| 176 | ): |
| 177 | """Wrapper to validate arguments and serialize return values using Pydantic.""" |
| 178 | try: |
| 179 | pydantic = importlib.import_module('pydantic') |
| 180 | except ModuleNotFoundError as ex: |
| 181 | raise ImproperlyConfigured('You need to install pydantic to use pydantic model serialization.') from ex |
| 182 | |
| 183 | BaseModel: typing.Type['BaseModel'] = pydantic.BaseModel # noqa: F811 # only defined when type checking |
| 184 | |
| 185 | if context is None: |
| 186 | context = {} |
| 187 | # A new dict, so the caller's dict isn't changed. |
| 188 | dump_kwargs = {'mode': 'json', **(dump_kwargs or {})} |
| 189 | |
| 190 | # If a file uses `from __future__ import annotations`, all annotations will |
| 191 | # be strings. `typing.get_type_hints()` can turn these back into real |
| 192 | # types, but can also sometimes fail due to circular imports. Try that |
| 193 | # first, and fall back to annotations from `inspect.signature()`. |
| 194 | task_signature = inspect.signature(task_fun) |
| 195 | |
| 196 | try: |
| 197 | type_hints = typing.get_type_hints(task_fun) |
| 198 | except (NameError, AttributeError, TypeError): |
| 199 | # Fall back to raw annotations from inspect if get_type_hints fails |
| 200 | type_hints = None |
| 201 | |
| 202 | def get_argument_model(arg_name, arg_value): |
| 203 | """Return the model the wrapper validates this argument with, or ``None``.""" |
| 204 | if type_hints and arg_name in type_hints: |
| 205 | arg_annotation = type_hints[arg_name] |
| 206 | else: |
| 207 | arg_annotation = task_signature.parameters[arg_name].annotation |
| 208 | |
| 209 | optional_arg = get_optional_arg(arg_annotation) |
| 210 | if optional_arg is not None and arg_value is not None: |
| 211 | arg_annotation = optional_arg |
| 212 | |
| 213 | if annotation_issubclass(arg_annotation, BaseModel): |
| 214 | return arg_annotation |
| 215 | return None |
| 216 | |
| 217 | def validate_argument(arg_model, arg_value): |
| 218 | return arg_model.model_validate( |
| 219 | arg_value, |
| 220 | strict=strict, |
| 221 | context={**context, 'celery_app': app, 'celery_task_name': task_name}, |
| 222 | ) |
| 223 | |
| 224 | @functools.wraps(task_fun) |
| 225 | def wrapper(*task_args, **task_kwargs): |
| 226 | # Validate task parameters if type hinted as BaseModel |
no test coverage detected