Thriftpy源代码走读(二)-Thrift文件加载

来源:互联网 发布:余姚数控编程培训 编辑:程序博客网 时间:2024/06/01 21:40

一、简述

通过前面的分析,我们知道无论是创建一个客户端还是服务器,第一步要做的就是调用thriftpy.load对thrift文件进行解析,并在内存中构建相应的module,本文将对load方法进行一个简单的分析。

二、load方法分析

  • load方法关键代码如下,该方法调用了parser模块中的parse方法对thrift文件进行解析,返回Thrift对象,并将该对象添加到sys.modules中(如果指定了module_name)
def load(path, module_name=None, include_dirs=None, include_dir=None):    real_module = bool(module_name)    thrift = parse(path, module_name, include_dirs=include_dirs,                   include_dir=include_dir)    if real_module:        sys.modules[module_name] = thrift    return thrift
  • parser模块的parse函数主要完成以下工作

    1. 初始化词法分析器 Lex和语法分析器 Yacc
    2. 读取文件内容保存到data变量中
    3. 创建一个空的module,并完成初始化
      thrift = types.ModuleType(module_name)
      setattr(thrift, '__thrift_file__', path)
    4. 调用语法分析器Yacc的parse方法对文件内容进行分析
      parser.parse(data)
  • 语法分析说明

    Thriftpy使用ply模块中的Lex和Yacc对thrift文件进行分析,关于该模块的使用方法这边不做详细介

    • thriftpy/parser/lexer.py文件中定义了词法分析规则
    • thriftpy/parser/parser.py文件中定义了语法分析规则,如:当语法分析器发现service语法时,将会调用p_simple_service方法对service内容进行解析生成对应的object,并将该object添加到前面创建的module中

三、其他加载方法

其他加载方法与load方法主要差别在于文件的读取方式,关键的解析部分完全一致
* load_fp方法
* load_module方法

四、小结

  • Thriftpy通过ply库中的Lex和Yacc完成thrift文件解析,并根据thrift文件内容在内存中构建出相应的module
原创粉丝点击