5

I am learning Python, and coding simple REST API using Flask micro-framework.

I am using SQLAlchemy for Object-relational-mapping and Marshmallow for Object-serialization/deserialization.

I am using snakecase for my variable names(according to PEP8).

I need to convert JSON object keys from camelcase to snakecase when receiving data from front-end(Angular) and vice versa, when returning response data.

What is the best approach to do this using Flask ?

I was unable to find a good answer on the internet.

4

1 回答 1

6

你不需要转换你的密钥,因为你不需要。数据不是代码,JSON 中的键不是变量。它们不受 PEP8 约束,您无需转换它们。

如果您有 JSON 对象键的约定,请在前端和后端的任何地方都遵守它。然后在加载和转储时使用字段的 Marshmallow 3.xdata_key参数来设置 JSON 文档中的键名。

例如

class UserSchema(Schema):
    first_name = fields.String(data_key="firstName")
    last_name = fields.Email(data_key='lastName')

如果您想为所有字段自动执行此操作,您可以提供自己的Schema.on_bind_field()实现data_key以从字段名称生成值:

import re
from functools import partial

from marshmallow import Schema

_snake_case = re.compile(r"(?<=\w)_(\w)")
_to_camel_case = partial(_snake_case.sub, lambda m: m[1].upper())

class CamelCasedSchema(Schema):
    """Gives fields a camelCased data key"""
    def on_bind_field(self, field_name, field_obj, _cc=_to_camel_case):
        field_obj.data_key = _cc(field_name.lower())

演示:

>>> from marshmallow import fields
>>> class UserSchema(CamelCasedSchema):
...     first_name = fields.String()
...     last_name = fields.String()
...
>>> schema = UserSchema()
>>> schema.load({"firstName": "Eric", "lastName": "Idle"})
{'first_name': 'Eric', 'last_name': 'Idle'}
>>> schema.dump({"first_name": "John", "last_name": "Cleese"})
{'firstName': 'John', 'lastName': 'Cleese'}

Marshmallow 文档的示例部分有一个类似的配方

如果您使用的是 Marshmallow 2.x,则需要设置两个参数:load_fromdump_to.

于 2019-06-09T14:01:48.613 回答