一个优雅的自动解决方案,用于从棉花糖模式和枚举生成/输出Typescript接口和枚举类。扩展亚丁·哈罗德的作品《锦葵》。

typemallow2的Python项目详细描述


类型锦葵2

一个优雅的自动解决方案,用于从棉花糖模式生成/输出Typescript接口

我更新了typemallow包,这样它就可以处理typescript和更新版本的malmallow中的枚举。 原著来自亚丁93。在

用法:

使用typemallow2很简单。

首先,安装软件包 pip install typemallow2

接下来,对于希望为其生成Typescript接口的棉花糖模式,只需从typemallow模块导入ts_interface和{},并将{}类修饰符前置到marshullow schema类中。在

生成Typescript接口所需的全部操作就是调用generate_ts()函数,并提供一个filepath作为参数来输出结果。在

主.py

fromtypemallow2importts_interface,generate_ts@ts_interface()classFoo(Schema):some_field=fields.Str()another_field=fields.Date()generate_ts('./output.ts')

输出.ts

^{pr2}$

typemallow甚至支持嵌套模式字段和枚举。在

主.py

fromtypemallow2importts_interface,generate_ts,ts_enumfrommarshmallowimportSchema,fieldsfrommarshmallow_enumimportEnumFieldfromenumimportEnum,auto@ts_enum(value_is_auto=True)classMyAutoEnum(Enum):enum1=auto()enum2=auto()@ts_enum(value_is_auto=False)classMyNonAutoEnum(Enum):enum1=100enum2=200enum3="Baguette"@ts_interface()classBoo(Schema):some_field=fields.Str()my_enum_field=EnumField(MyAutoEnum)@ts_interface()classFoo(Schema):some_field=fields.Str()another_field=fields.Str()my_field=fields.Bool()my_interface_field=fields.Nested(Boo,many=False)generate_ts('./output.ts')

输出.ts

exportenumMyAutoEnum{enum1,enum2,}exportinterfaceBar{some_field: string;my_enum_field: MyAutoEnum;}exportinterfaceFoo{some_field: string;another_field: string;my_field: boolean;my_interface_field: Bar;my_interfaces_fields: Bar[];}

扩展使用:

@ts_interface()decorator函数接受可选参数context,默认值为。。。嗯…'“默认值”。在

为什么会这样?

当一个棉花糖模式用@ts_interface修饰符标识时,它被添加到模式字典中的列表中,字典键是提供给context参数的值。如果要为每个模式提供不同的上下文,则会创建不存在的附加键,或者只将模式附加到现有键的列表中。在

这很方便,因为generate_ts()函数接受一个可选的context参数,它只过滤字典中特定键的模式。在

如果您希望将不同的上下文输出到不同的文件,例如

主.py

...fromtypemallow2importts_interface,generate_ts@ts_interface(context='internal')classFoo(Schema):foo=fields.Str()@ts_interface(context='internal')classBar(Schema):bar=fields.Str()@ts_interface(context='external')classFooBar(Schema):foo_bar=fields.Str()''' we're telling typemallow2 that we only want to generate interfaces from Schemas with an 'internal' context to './internal.ts' '''generate_ts('./internal.ts',context='internal')''' only generate interfaces from Schemas with an 'external' context to './external.ts' '''generate_ts('./external.ts',context='external')

内部.ts

exportinterfaceFoo{foo: string;}exportinterfaceBar{bar: string;}

外部.ts

exportinterfaceFooBar{foo_bar: string;}

欢迎加入QQ群-->: 979659372 Python中文网_新手群

推荐PyPI第三方库


热门话题
java如何使用数据库中的值填充p:selectOneMenu   Java/Junit中的异步单元测试一个非常简单但不成功的例子   在Debian上使用Java连接到MySQL   java测试时如何恢复表中的一条记录/行?   java如何将重点放在jbutton上而不是放在另一个jbutton上?   java我可以从HPROF文件中获取JVM标志吗?   java如何使用自定义比较器在2个集合上保留   java让stringTokenizer将一行文本拆分为预定义变量的最佳方法是什么   Kotlin Android/Java字符串日期时间格式,API21   exchange server EWS Java Api自动发现不工作   netbeans是Java新手,似乎无法修复错误;应为类、接口或枚举。274062   我正在尝试将一些scala代码转换为Java8,以创建新的Lambda和并行集合   流中的分配api(java)   用于串行通信的java Python字节数组