简体   繁体   中英

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.

data directory:

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

on my app.py I have this code:

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

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. 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

It seems app.py has not been loaded as part of the package hierarchy (ie src and order packages have not been loaded). You should be able to run

from src.order import app

from the parent directory of src and your code will work. 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.

However, I do not believe you need the .validator in your case since both modules are in the same directory. You should be able to do

from validator import validate

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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