简体   繁体   English

使用 aws sam 时有没有办法修复 pythonpath?

[英]Is there a way to fix the pythonpath when using aws sam?

I'm trying to import a custom module that I created, but it breaks my API just to import it.我正在尝试导入我创建的自定义模块,但它破坏了我的 API 只是为了导入它。

data directory:数据目录:

-src
--order
----__init__.py
----app.py
----validator.py
----requirments.txt
--__init__.py

on my app.py I have this code:在我的 app.py 我有这个代码:

import json
from .validator import validate

def handler(event, context):
    msg = ''
    if event['httpMethod'] == 'GET':
        msg = "GET"
    elif event['httpMethod'] == 'POST':
        pass    #msg = validate(json.loads(event['body']))

    return {
        "statusCode": 200,
        "body": json.dumps({
            "message": msg,
        }),
    }

I get this error:我收到此错误:

Unable to import module 'app': attempted relative import with no known parent package无法导入模块“app”:尝试在没有已知父 package 的情况下进行相对导入

However, if I remove line 2 ( from.validator import validate ) from my code, it works fine, so the problem is with that import , and honestly, I can't figure what is going on.但是,如果我从我的代码中删除第 2 行( from.validator import validate ),它工作正常,所以问题出在那个import上,老实说,我不知道发生了什么。 I have tried to import using:我尝试使用以下方式导入:

from src.order.validator import validate

but it doesn't work either.但它也不起作用。

was able to solve my issue by generating a build through the command: sam build, and zipping my file, and putting it on the root folder inside aws-sam, it's not a great solution because I have to rebuild at every small change, but at least it's a workaround for now能够通过以下命令生成构建来解决我的问题:sam build,然后压缩我的文件,并将其放在 aws-sam 内的根文件夹中,这不是一个很好的解决方案,因为我必须在每一个小的更改时重新构建,但是至少现在是一种解决方法

It seems app.py has not been loaded as part of the package hierarchy (ie src and order packages have not been loaded).似乎app.py尚未作为 package 层次结构的一部分加载(即尚未加载srcorder包)。 You should be able to run你应该能够运行

from src.order import app

from the parent directory of src and your code will work.src的父目录中,您的代码将起作用。 If you run python app.py from the terminal — which I assume is what you did — app.py will be run as a standalone script — not as part of a package.如果你从终端运行python app.py我假设你就是这样做的app.py将作为独立脚本运行——而不是作为 package 的一部分运行。

However, I do not believe you need the .validator in your case since both modules are in the same directory.但是,我认为您不需要.validator ,因为两个模块都在同一个目录中。 You should be able to do你应该能够做到

from validator import validate

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

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