marshmallow-code / marshmallow-code/marshmallow
Custom error message for unknown when dump only
Nobody has claimed this yet.
- Dominant language
- Python
- Stars
- 7.2k
- Forks
- 738
- Avg merge
- 1d 23h
- Merged PRs (30d)
- 7
Description
I'm just getting started with marshmallow so if there's a more elegant way to solve the issue please let me know.
I have the following simple model and schema.
class Instance(db.Model):
__tablename__ = 'instances'
id = db.Column(db.Integer, primary_key=True)
hostname = db.Column(db.Unicode, index=True, unique=True, nullable=False)
port = db.Column(db.Integer, nullable=False)
def __repr__(self):
return '<Instance: {}>'.format(self.hostname)
class InstanceSchema(Schema):
id = fields.Integer(dump_only=True)
hostname = fields.String(
required=True,
error_messages={'required': {'message': 'Hostname required', 'code': 400}}
)
port = fields.Integer(
required=True,
error_messages={'required': {'message': 'Port required', 'code': 400}}
)
@validates_schema
def at_least_one(self, data):
if self.partial and not len(data.keys()):
raise ValidationError('Provide at least one valid key')
As you can see id is dump_only. If I try to load a simple dict (in the real application this would be data of a PATCH request)
try:
result = InstanceSchema(partial=True).load({'id': 4})
print(result)
except ValidationError as err:
print(err.messages)
I'll get that id is an unknown field. So I have to manually check for it to provide a better error message like
if "id" in err.messages:
err.messages["id"] = "id is readonly"
It would be cool if it was possible to have a custom error message like hostname or port like
id = fields.Integer(dump_only=True,
error_messages={'dump_only': {'message': 'id is readonly', 'code': 400}}
)
Contributor guide
First steps
- Read the whole issue, then the project's contributing guide.
- Comment on the issue to say you are picking it up — it saves two people doing the same work.
- Fork the repository and make your change on a branch.
- Open a pull request that references the issue number.
Research direction
No file or test is named in the issue. Start by tracing how Schema fields.Integer(dump_only=True) produces the unknown-field ValidationError during load, then inspect the existing error_messages handling; done means a dump-only field can provide the requested custom message and the behavior is covered by a test.
Written by the indexing model from the issue text.
Assessment
- Tech stack
- python
- Domain
- backend-api-design
- Issue type
- Feature
- Difficulty
- 3/5
- Estimated time
- 1-2 days
- Activity status
- Stale
- Clarity
- Mostly clear
- Newbie friendliness
- 38/100