一个优雅的自动解决方案,用于从棉花糖模式和枚举生成/输出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无法启动应用程序:JNLP错误   java根据用户输入在PreparedStatement中使用setTime()或setNull()   java EJB与同步   java以object为键通过hashmap进行搜索   java中的模10^9+7   针对包含其他对象的对象的java OOP最佳实践   如何将字符串作为HTML代码从Java文件读取到JSP页面?   java我的POM怎么了?“解析表达式..检测到递归表达式循环”   用于Hbase的Mapreduce的java NoSuchMethodError   JAVAlang.SecurityException:权限拒绝:启动意图{act=安卓.Intent.action.MAIN cat=[安卓.Intent.category.LAUNCHER]   数组初始化谜语Java   通过arraylist搜索时的java句柄关联