Py学习  »  Python

Python+Flask REST API,如何在camelcase和snakecase之间转换数据密钥?

Yoh0xFF • 4 年前 • 973 次点击  

我正在学习Python,并使用 Flask 微观框架。

我在用 SQLAlchemy 对于对象关系映射和 Marshmallow 用于对象序列化/反序列化。

我使用snakecase作为变量名(根据 PEP8 ).

当从前端(角度)接收数据时,我需要将JSON对象键从camelcase转换为snakecase,反之亦然,当返回响应数据时。

使用烧瓶的最佳方法是什么?

我在网上找不到一个好的答案。

Python社区是高质量的Python/Django开发社区
本文地址:http://www.python88.com/topic/48970
 
973 次点击  
文章 [ 1 ]  |  最新文章 4 年前
Martijn Pieters
Reply   •   1 楼
Martijn Pieters    4 年前

你不需要转换密钥,因为你不需要。数据不是代码,json中的键不是变量。他们不受PEP8的约束,你也不会改变他们。

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

例如。

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

如果您想自动化所有字段,可以提供自己的 Schema.on_bind_field() implementation 生成 数据键 字段名中的值:

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'}

棉花糖文档的示例部分有 similar recipe 是的。

如果使用的是棉花糖2.x,则需要设置两个参数: load_from dump_to 是的。