新的__init__.py处理破坏了旧模块

时间:2019-04-22 11:58:01

标签: python-3.x sys.path

我是一位相当新手的Python开发人员,正在研究别人的代码。他编写了一个依赖于__init__.py的模块,其中提供了可作为烧瓶应用程序的一部分动态调用的模块列表。

在Python 3.3+中,如果存在__init__.py文件,则找不到模块。如果我们删除__init__.py,则动态模块发现将不起作用。

我们尝试按照几篇关于3.3+中新__init__.py vs sys.path()行为的指南并删除 init 来解决无法找到模块的问题。 py这样可以解决导入时无法找到模块的问题,但会破坏动态发现。

__init__.py

from os.path import dirname, basename, isfile
import glob
modules = glob.glob(dirname(__file__)+"/*.py")
__all__ = [ basename(f)[:-3] for f in modules if isfile(f) and not f.endswith('__init__.py')]

base_processor.py

class BaseProcessor(object):

    """
    This is a base class for all processors that handle API requests from AWS API Gateway

    Attributes:
        MAX_SIZE    The maximum size that elastic search accepts

    """
    MAX_SIZE = 214748364

    def __init__(self):
        super(BaseProcessor, self).__init__()


    def getApiConfig(self):
        """
            This method defines what this processor handles and is required to be defined so the
            dynamic loading of all processors functions correctly.  Subclasses should overide it.
        """
        raise Exception("Concrete implementation of this BaseProcessor class did not implement the getApiConfig function.")

    def process(self, event):
        """
            This method is the entry point for  all processors and is expected to be
            implemented by the sub class.  Its base implementation will throw an error
        """
        raise Exception("Concrete implementation of this BaseProcessor class did not implement the process function.")

    def getFirstAgregationKey(self, results, field_name):

        return_results = ""

        if field_name in results and len(results[field_name]["buckets"]) > 0:
            return_results = results[field_name]["buckets"][0]["key"]

        return return_results

调用base_processor以获得可用处理器列表的代码。

processors = []
EventProcessors = BaseProcessor.__subclasses__()
for processor in EventProcessors:
    processor_instance = processor()
    processors.append(processor_instance.getApiConfig())

flask应用程序运行时,处理器数组为空,并且app.route()调用均未找到处理器来处理其调用。

0 个答案:

没有答案