Category:PYTHON
Article From:https://www.cnblogs.com/navysummer/p/9122671.html

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

    1. Initializing lexical analyzer Lex and parser Yacc
    2. Read the content of the file to the data variable
    3. Create an empty module and complete the initialization
      thrift = types.ModuleType(module_name) 
      setattr(thrift, '__thrift_file__', path)
    4. Invoke the parse method of parser Yacc to analyze the contents of files.
      parser.parse(data)
  • Grammatical analysis

    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.
* load_fpMethod
* load_moduleMethod

> 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.
 
Link of this Article: Thrift file loading

Leave a Reply

Your email address will not be published. Required fields are marked *