热门标签 | HotTags
当前位置:  开发笔记 > 编程语言 > 正文

Supportfieldnamesthataren'tvalidPythonidentifiers

Iwanttosupportafieldcalledfrom,butIcantdothisinmarshmallowbecauseitw

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



   



推荐阅读
author-avatar
清澈小溪-
这个家伙很懒,什么也没留下!
PHP1.CN | 中国最专业的PHP中文社区 | DevBox开发工具箱 | json解析格式化 |PHP资讯 | PHP教程 | 数据库技术 | 服务器技术 | 前端开发技术 | PHP框架 | 开发工具 | 在线工具
Copyright © 1998 - 2020 PHP1.CN. All Rights Reserved | 京公网安备 11010802041100号 | 京ICP备19059560号-4 | PHP1.CN 第一PHP社区 版权所有