从thrift到pyi转换
pyi是什么?为什么要用pyi?可见官方解释
The *.pyi files are used by PyCharm and other development tools to
provide more information, such as PEP 484 type hints, than it is able
to glean from introspection of extension types and methods. They are
not intended to be imported, executed or used for any other purpose
other than providing info to the tools. If you don’t use use a tool
that makes use of .pyi files then you can safely ignore this file.See: https://www.python.org/dev/peps/pep-0484/
https://www.jetbrains.com/help/pycharm/2016.1/type-hinting-in-pycharm.html
简单来说就是存根文件,文件包含普通Python模块的类型提示信息,可以帮我们增加thrift的类型提示。为了方便使用,将thrift转换为pyi的方式,方便class的查找,具体使用方式:
pip install thrift2pyi
thrift2pyi [src_file]
p.s.: pyi文件会自动存放在py的同级别目录下
json到thrift转换
- 将任意字典转换为对应的结构体
import pip
def json_thrift_convertor(src_json, dest_struct, ignore_unknow_key=False):
"""
@src_json: dict loads from user pass json body
@dest_struct: final thrift type after parse
@ignore_unknow_key: default False, if one key in src_json but not
in thrift proto define, throw an exception(False) or just
ignore(True)
"""
current_k = None
current_v = None
try:
# import pdb
# pdb.set_trace()
for (k, v) in src_json.items():
current_k = k
current_v = v
# 此处需要进行field检查,确认对应的field`s在thrift结构的proto定义中,
# 此处如果不加检查,其实__setattr__依然可以给目的结构加入不存在的key
if k not in dest_struct._tspec:
if not ignore_unknow_key:
print(