-
-
Notifications
You must be signed in to change notification settings - Fork 310
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Pydantic serialization #660
Comments
We are using this snippet: import json
from functools import partial
from typing import Any
from typing import Callable
from typing import Dict
from typing import Optional
from typing import TypeVar
from typing import cast
from dramatiq.message import Message
from dramatiq.actor import Actor
from dramatiq.actor import actor
from pydantic import BaseModel
from pydantic import validate_arguments
from pydantic.decorator import V_DUPLICATE_KWARGS
from pydantic.decorator import V_POSITIONAL_ONLY_NAME
R = TypeVar('R')
class PydanticActor(Actor):
def __init__(self, fn: Callable[..., R], **kwargs):
super().__init__(validate_arguments(fn), **kwargs)
def message_with_options(
self,
*,
args: tuple = (),
kwargs: Optional[Dict[str, Any]] = None,
**options,
) -> Message[R]:
assert not args, 'positional arguments are not allowed in pydantic model'
instance = cast(BaseModel, self.fn.model(*args, **kwargs))
# exclude extra fields created by `validate_arguments`
exclude = {
V_POSITIONAL_ONLY_NAME,
V_DUPLICATE_KWARGS,
self.fn.vd.v_args_name,
self.fn.vd.v_kwargs_name,
}
json_kwargs = json.loads(instance.json(exclude=exclude))
return super().message_with_options(args=args, kwargs=json_kwargs, **options)
def send(self, /, **kwargs) -> Message[R]:
# positional arguments are not allowed in pydantic model
return super().send(**kwargs)
pydantic_actor = partial(actor, actor_class=PydanticActor) But this actor has one limitation: it can't be used with asyncio due |
It also does not support Pydantic/type checked return values right? |
Yes. We do not need it because do not use result backend |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
I'm tinkering with an automatic Pydantic (de)serialization integration. Here is what I have so far:
broker
instance to fetch the actor function's return typeMessage
class to makeget_result
convert the result to the actor function's return typeThe text was updated successfully, but these errors were encountered: