SwaggerHub导出Python SDK时因小写转换致键重复问题
问题原因
这是OpenAPI代码生成器(包括SwaggerHub、editor.swagger.io及openapi-generator使用的核心引擎)的命名规范化策略缺陷导致的:
- 生成器默认会将OpenAPI定义中的字段名转换为小写(符合Python变量名的常规风格),但仅做简单的大小写转换,未处理"大小写不同但小写后重名"的字段(比如
M和m转小写后都是m,T和t转小写后都是t)。 - Python字典不允许重复键,生成代码时后出现的重复键会覆盖前一个,最终导致属性映射和类型定义出现冲突。
解决方法
1. 自定义生成器命名规则(推荐)
使用openapi-generator-cli生成SDK时,通过参数强制保留原始字段名的大小写,或者指定自定义命名规则避免冲突:
# 强制保留原始字段名的大小写 openapi-generator-cli generate -i binance-spot-api.yaml -g python -o binance-sdk --naming-convention=original
如果需要更友好的Python风格命名,可配合x-codegen-name扩展(见方法3),再用蛇形命名策略。
2. 手动修正生成后的代码
直接修改生成的agg_trade.py文件,给冲突字段重命名并同步映射关系:
传统Swagger SDK版本
swagger_types = { 'a': 'int', 'p': 'str', 'q': 'str', 'f': 'int', 'l': 'int', 'timestamp': 'bool', # 替换原`t` 'is_maker': 'bool', # 替换原第一个`m` 'is_best_match': 'bool'# 替换原第二个`m` } attribute_map = { 'a': 'a', 'p': 'p', 'q': 'q', 'f': 'f', 'l': 'l', 'timestamp': 'T', # 映射到原始字段`T` 'is_maker': 'm', # 映射到原始字段`m` 'is_best_match': 'M' # 映射到原始字段`M` }
Pydantic版本
class AggTrade(BaseModel): """AggTrade""" # noqa: E501 a: StrictInt = Field(description="Aggregate tradeId") p: StrictStr = Field(description="Price") q: StrictStr = Field(description="Quantity") f: StrictInt = Field(description="First tradeId") l: StrictInt = Field(description="Last tradeId") timestamp: StrictBool = Field(description="Timestamp", alias="T") is_maker: StrictBool = Field(description="Was the buyer the maker?", alias="m") is_best_match: StrictBool = Field(description="Was the trade the best price match?", alias="M") __properties: ClassVar[List[str]] = ["a", "p", "q", "f", "l", "T", "m", "M"]
3. 修改原始OpenAPI定义(若有权限)
如果能编辑Binance的OpenAPI文档,给冲突字段添加x-codegen-name扩展,指定生成代码时的变量名:
aggTrade: type: object properties: # ... 其他字段省略 ... T: type: boolean description: Timestamp example: 1498793709153 x-codegen-name: timestamp m: type: boolean description: Was the buyer the maker? x-codegen-name: is_maker M: type: boolean description: Was the trade the best price match? x-codegen-name: is_best_match
生成器会优先使用x-codegen-name指定的名称,避免大小写冲突。
内容的提问来源于stack exchange,提问作者hedgedandlevered
相关产品推荐
相关产品推荐

