作者:清澈小溪- | 来源:互联网 | 2023-10-13 11:15
I want to support a field called "from", but I can't do this in marshmallow because it would cause a syntax error:
1 2 3
| python
class MySchema(Schema):
from = fields.Nested(OtherSchema, attribute="my_attribute") |
This got me thinking -- marshmallow is kind of backwards, isn't it? The field that comes in from the outside world is the one that has to be specified as a valid Python identifier, and the field that you're actually going to work with in your code is specified as a string. Shouldn't they be swapped? I'm sure other folks are going to want to parse in or write out a value that isn't a valid Python identifier sometimes.
1 2 3
| python
class MySchema(Schema):
my_attribute = fields.Nested(OtherSchema, field="from") |
This could even be made backward compatible with existing Marshmallow stuff, like so:
- If neither "field" nor "attribute" are specified, the field and attribute values are both the same as the lvalue, so there's no issue.
- If "attribute" is specified, the lvalue is used for "field"
- if "field" is specified, the lvalue is used for "attribute"
Probably harder for you to actually implement this sorta thing though, but it's a thought.
该提问来源于开源项目:marshmallow-code/marshmallow
Is there a way to disallow fields which are python identifiers when allowing unknown keys?
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22
| class OrderLabelSchema(marshmallow.Schema):
class Meta:
unknown = marshmallow.INCLUDE
discriminator = marshmallow.fields.Str(
required=True, validate=marshmallow.validate.OneOf(base.TYPES)
)
class OrderSchema(marshmallow.Schema):
class Meta: fields = (
'created_at',
'updated_at',
'id',
'labels',
'status',
)
labels = marshmallow.fields.Nested(OrderLabelSchema)
status = marshmallow.fields.Str(
validate=marshmallow.validate.OneOf(STATUSES)
) |
I ended up writing my own validator, but I was thinking this might not be the correct approach:
1 2 3 4 5 6 7 8 9 10 11
| .pre_load
def validate_keys(self, data, **kwargs):
errors = {
k: ['Invalid identifier provided.']
for k, _ in data.items()
if not k.isidentifier()
}
if errors:
raise marshmallow.exceptions.ValidationError(errors)
return data |