python序列化框架Marshmallow

 nadia     2020-03-26     1527     0   

欢迎来到银盒子的世界~

很好用的的一个python框架,在这里记录一下。他的文档在这里(https://marshmallow.readthedocs.io/en/latest/)

Marshmallow是一个与ORM / ODM /框架无关的库,用于将复杂的数据类型(例如对象)与本机Python数据类型之间进行转换。


简而言之,棉花糖模式可用于:

  • 验证输入数据。(比如逼格json数据内容不对,比如少一个或者多一个,就会报错)

  • 输入数据反序列化为应用程序级对象。  (意思就是把一个json数据,转换成一个对象,可以直接用)

  • 应用程序级对象序列化为原始Python类型。然后可以将序列化的对象呈现为标准格式,例如JSON,以用于HTTP API。

简单举例一下一个用法,可以用于根据架构验证配置,比如,验证package.json文件


1.新建文件examples/package_json_example.py  ↓↓↓↓

import sys

import json

from packaging import version

from marshmallow import schema, fields,INCLUDE,pprint,ValidationError


class Version(fields.Field):

    """Version field that deserializes to a Version object."""

    def _deserialize(self, value, *args, **kwargs):

        try:

            return version.Version(value)

        except version.InvalidVersion:

            raise ValidationError("Not a valid version.")

 

    def _serialize(self, value, *args, **kwargs):

        return str(value)

class PackageSchema(Schema):

    name = fields.Str(required=True)

    version = Version(required=True)

    description = fields.Str(required=True)

    main = fields.Str(required=False)

    homepage = fields.URL(required=False)

    scripts = fields.Dict(keys=fields.Str(), values=fields.Str())

    license = fields.Str(required=True)

    dependencies = fields.Dict(keys=fields.Str(), values=fields.Str(), required=False)

    dev_dependencies = fields.Dict(

        keys=fields.Str(),

        values=fields.Str(),

        required=False,

        data_key="devDependencies",

    )

    class Meta:

        # Include unknown fields in the deserialized output

        unknown = INCLUDE

if __name__ == "__main__":

    pkg = json.load(sys.stdin)

    try:

        pprint(PackageSchema().load(pkg))

    except ValidationError as error:

        print("ERROR: package.json is invalid")

        pprint(error.messages)

        sys.exit(1)


2.然后有下边这个json文件,invaild_package.json  ↓↓↓

{

  "name": "dunderscore",

  "version": "1.2.3",

  "description": "The Pythonic JavaScript toolkit",

  "devDependencies": {

    "pest": "^23.4.1"

  },

  "main": "index.js",

  "scripts": {

    "test": "pest"

  },

  "license": "MIT"

}


3.然后直接执行命令行,验证这个json文件

$ python examples/package_json_example.py < package.json

{'description': 'The Pythonic JavaScript toolkit',

'dev_dependencies': {'pest': '^23.4.1'},

'license': 'MIT',

'main': 'index.js',

'name': 'dunderscore',

'scripts': {'test': 'pest'},

'version': <Version('1.2.3')>}


4.假如这个json有问题,出错了,就会跑出一个错误来

$ python examples/package_json_example.py < invalid_package.json

ERROR: package.json is invalid

{'homepage': ['Not a valid URL.'], 'version': ['Not a valid version.']}


其他例子,可以直接看官方文档(https://marshmallow.readthedocs.io/en/latest/examples.html)





比如我经常用flask框架  那就可以用用flask_marshmallow   git地址在这里(https://github.com/marshmallow-code/flask-marshmallow)



发表评论