繁体   English   中英

无法在 __init__.py 中导入定义的模块

[英]Failed to import defined modules in __init__.py

我的目录如下所示:

- HttpExample:
    - __init__.py
    - DBConnection.py
    - getLatlong.py

我想在__init__.py import DBConnectionimport getLatlong 我的__init__.py没有错误,直到我运行它,我收到:

System.Private.CoreLib:执行函数时出现异常:Functions.HttpExample。 System.Private.CoreLib:结果:失败异常:ModuleNotFoundError:没有名为“getLatlong”的模块

我试图在 getLatlong 中使用函数来使用用户从__init__.pygetLatlong输入的信息。 下面是代码:

__init__.py

from getLatlong import result
from DBConnection import blobService, container_name, account_key, file_path


def main(req: func.HttpRequest) -> func.HttpResponse:
    logging.info('Python HTTP trigger function processed a request.')

    section = req.params.get('section')
    bound = req.params.get('bound')
    km_location = req.params.get('km_location')
    location = req.params.get('location')
    if not section:
        try:
            req_body = req.get_json()
        except ValueError:
            pass
        else:
            section = req_body.get('section')

    if section and bound and km_location:

        result(section, km_location, bound, location).getResult() #HERE

        return func.HttpResponse(f"Hello {section}, {bound}!")

    #elif section is None or bound is None or km_location is None:
    #    return func.HttpResponse("All values are mandatory!")

我还在getLatlong处收到编译错误以将DBConnection导入此类。 以下值将传递给getLatlong.py 编码 :

from DBConnection import blobService, container_name, account_key, file_path #Another import error here says : Unable to import DBConnection

class result:
    def __init__(self, section, bound, km_location, location):
        self.section = section
        self.bound = bound
        self.km_location = km_location
        self.location = location

    def getResult(self):

        print(self.section)
        print(self.bound)
        print(self.km_location)
        print(self.location)

在我失去理智之前,我已经尝试了各种方法来导入这些文件。

您会收到这些错误,因为 Python 不知道在哪里查找要导入的文件。 根据您使用的 Python 版本,我看到了三种解决此问题的方法:

  1. 您可以将HttpExample添加到您的 PYTHONPATH 中,然后您的导入应该像您目前拥有的那样工作。

  2. 另一种方法是使用sys模块并将路径附加到HttpExample ,例如

import sys
sys.path.append('PATH/TO/HttpExample')

但是您必须在所有文件中执行此操作,您希望从父文件夹导入某些内容。

  1. 或者你使用相对导入,它从 Python 2.5 开始就可用(参见 PEP238)。 这些仅在模块中可用,但是当您拥有__init__.py文件时,它应该可以工作。 对于相对导入,您使用的是 dots . 告诉 Python 在哪里寻找导入。 一个点. 告诉 Python 在父文件夹中查找所需的导入。 您也可以使用..上升两个级别。 但是在您的情况下,一个级别就足够了。

因此,在您的情况下,将代码更改为此,应该可以解决您的问题。

__init.py__

from .getLatlong import result
from .DBConnection import blobService, container_name, account_key, file_path

getLangLong.py

from .DBConnection import blobService, container_name, account_key, file_path

您可以尝试from __app__.HttpExample import getLatlong

共享代码文件夹中有关于如何导入模块的文档。 检查此文档: 文件夹结构

它说共享代码应该保存在__app__中的单独文件夹中。 在我的测试中,这对我有用。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM