Bridge(支持枚举类型)

简介

下面的例子中,如果返回的字段类型为枚举类型,框架会自动转换为枚举对象的value。如果枚举对象有show成员,则框架默认会把枚举对象转化为{'value': ..., 'show': ...}格式的dict。

示例

from enum import Enum
from lessweb import Application, Model

def load_enum(obj, real_type):
    if issubclass(real_type, Enum):
        if isinstance(obj, str) and obj.isdigit():
            return real_type(int(obj))
        else:
            return real_type(obj)

def dump_enum(source):
    if isinstance(source, Enum):
        return {'value': source.value, 'show': source.show} \
            if hasattr(source, 'show') else source.value

class Rank(Enum):
    A = 'A'
    B = 'B'
    C = 'C'

class Gender(Enum):
    MALE = 1
    FEMALE = 2

Gender.MALE.show = '男'
Gender.FEMALE.show = '女'

class User:
    id: int
    gender: Gender
    rank: Rank

def add_user(user: Model[User]):
    return user()

app = Application()
app.add_post_mapping('/user', dealer=add_user)
app.add_request_bridge(load_enum)
app.add_response_bridge(dump_enum)
app.run()

请求: curl -X POST -d "id=6&rank=C&gender=1" "http://localhost:8080/user"
返回: {"id": 6, "gender": {"value": 1, "show": "男"}, "rank": "C"}