Skip to content
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

multiple fields in validates decorator #1965

Open
wants to merge 2 commits into
base: dev
Choose a base branch
from
Open
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Next Next commit
multiple fields in validates decorator
dharani7998 committed Mar 24, 2022
commit a01fbaaecc37bb12191bff09da9e6979dea7834a
4 changes: 2 additions & 2 deletions src/marshmallow/decorators.py
Original file line number Diff line number Diff line change
@@ -77,12 +77,12 @@ class MarshmallowHook:
) # type: Optional[Dict[Union[Tuple[str, bool], str], Any]]


def validates(field_name: str) -> Callable[..., Any]:
def validates(*field_names: str) -> Callable[..., Any]:
"""Register a field validator.

:param str field_name: Name of the field that the method validates.
"""
return set_hook(None, VALIDATES, field_name=field_name)
return set_hook(None, VALIDATES, field_names=field_names)
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Should we try to preserve this hook interface for a minor release? The docstring for set_hook says "You should not need to use this method directly". Any objection to making validates return a wrapper that loops the calls to set_hook instead?

Copy link
Author

@dharani7998 dharani7998 Mar 25, 2022

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I don't see how the wrapper will work if we loop and call set_hook, __marshmallow_hook__[VALIDATES] value gets overwritten each time and ends with the last argument passed in the validates decorator.

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

It won't work, try this. It will only register the last field given in the decorator

from marshmallow import (
    Schema,
    fields,
    pre_dump,
    post_dump,
    pre_load,
    post_load,
    # pre_validate,
    validates,
    validates_schema,
    ValidationError,
    EXCLUDE,
    INCLUDE,
    RAISE,
)

class TestValidates(Schema):
    value = fields.Str()
    another_value = fields.Str()
    
    @validates('value', 'another_value')
    def validates_function(self, data, **kwargs):
        print(f'Inside validates: {{ {data}:{data} }}')


schema = TestValidates()
print(schema._hooks['validates'])
validator = getattr(schema, schema._hooks['validates'][0])
print(validator.__marshmallow_hook__)
print()



schema.load({
    'value': 'value',
    'another_value': 'another_value'
})



def validates_schema(
59 changes: 30 additions & 29 deletions src/marshmallow/schema.py
Original file line number Diff line number Diff line change
@@ -1097,22 +1097,38 @@ def _invoke_field_validators(self, *, error_store: ErrorStore, data, many: bool)
for attr_name in self._hooks[VALIDATES]:
validator = getattr(self, attr_name)
validator_kwargs = validator.__marshmallow_hook__[VALIDATES]
field_name = validator_kwargs["field_name"]
field_names = validator_kwargs["field_names"]

try:
field_obj = self.fields[field_name]
except KeyError as error:
if field_name in self.declared_fields:
continue
raise ValueError(f'"{field_name}" field does not exist.') from error
for field_name in field_names:
try:
field_obj = self.fields[field_name]
except KeyError as error:
if field_name in self.declared_fields:
continue
raise ValueError(f'"{field_name}" field does not exist.') from error

data_key = (
field_obj.data_key if field_obj.data_key is not None else field_name
)
if many:
for idx, item in enumerate(data):
data_key = (
field_obj.data_key if field_obj.data_key is not None else field_name
)
if many:
for idx, item in enumerate(data):
try:
value = item[field_obj.attribute or field_name]
except KeyError:
pass
else:
validated_value = self._call_and_store(
getter_func=validator,
data=value,
field_name=data_key,
error_store=error_store,
index=(idx if self.opts.index_errors else None),
)
if validated_value is missing:
data[idx].pop(field_name, None)
else:
try:
value = item[field_obj.attribute or field_name]
value = data[field_obj.attribute or field_name]
except KeyError:
pass
else:
@@ -1121,24 +1137,9 @@ def _invoke_field_validators(self, *, error_store: ErrorStore, data, many: bool)
data=value,
field_name=data_key,
error_store=error_store,
index=(idx if self.opts.index_errors else None),
)
if validated_value is missing:
data[idx].pop(field_name, None)
else:
try:
value = data[field_obj.attribute or field_name]
except KeyError:
pass
else:
validated_value = self._call_and_store(
getter_func=validator,
data=value,
field_name=data_key,
error_store=error_store,
)
if validated_value is missing:
data.pop(field_name, None)
data.pop(field_name, None)

def _invoke_schema_validators(
self,