Python自动化测试(1) : json到thrift转换

本文介绍了如何将thrift转换为pyi文件以提供类型提示,以及如何进行json到thrift的转换。在转换过程中提到了thrift文件定义导致的变量类型问题,并给出了python代码转pyi后的本地调试方法,包括解决NoModule错误的调试技巧。
摘要由CSDN通过智能技术生成

从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(
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值