1″ and “brief introduction”
From the previous analysis, we know that the first step to do, whether to create a client or a server, is to call thriftpy.load to parse the thrift file and build the corresponding module in memory. This article will make a simple division of the load method.Analysis.
two, load method analysis
- loadThe method key code is as follows, which calls the parse method in the parser module to parse the thrift file, returns the Thrift object, and adds the object to the sys.modules (if module_name) is added.
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
parserThe parse function of the module completes the following work
- Initializing lexical analyzer Lex and parser Yacc
- Read the content of the file to the data variable
- Create an empty module and complete the initialization
thrift = types.ModuleType(module_name)
setattr(thrift, '__thrift_file__', path)
- Invoke the parse method of parser Yacc to analyze the contents of files.
ThriftpyUsing the Lex and Yacc in the ply module to analyze the thrift file, there is no detail about the way to use the module.
- thriftpy/parser/lexer.pyThe word analysis rules are defined in the file
- thriftpy/parser/parser.pyThe syntax parsing rules are defined in the file, such as: when the parser finds the service syntax, the p_simple_service method will be called to parse the service content to generate the corresponding object and add the object to the M created earlier.In odule
three, other loading methods
The main difference between other loading methods and load methods is the way of reading files, and the key parsing parts are identical.
> four, summary
- ThriftpyThrift file parsing is accomplished through Lex and Yacc in the ply library, and the corresponding module is built in memory according to the contents of thrift files.