首页 > 解决方案 > {“errorMessage”:“无法导入模块'app':没有名为'app'的模块”,“errorType”:“Runtime.ImportModuleError”}

问题描述

我正在关注https://docs.aws.amazon.com/lambda/latest/dg/services-rds-tutorial.html

我在我正在做的最后$ aws lambda invoke --function-name CreateTableAddRecordsAndRead output.txt

我收到一个找不到 pymysql 的错误,所以我看到了一个关于 pip 将包安装到您的 zip 文件的教程:https ://docs.aws.amazon.com/lambda/latest/dg/python-package.html

现在我有以下文件夹结构

$ ls aws_mysql_tutorial
__init__.py  app.py  output.txt  package/

我已经压缩了这个文件夹并更新了这个 lambda 的代码

$ aws lambda update-function-code --function-name CreateTableAddRecordsAndRead --zip-file "fileb://aws_mysql_tutorial.zip"

现在我收到一条新的错误消息

{"errorMessage": "Unable to import module 'app': No module named 'app'", "errorType": "Runtime.ImportModuleError"}

这让我很困惑,因为我压缩的代码有一个 init 文件和一个名为 app.py 的 python 文件。现在它有了 pymysql 包,我不再遇到旧错误。

app.py 与教程页面中间显示的相同

import sys
import logging
import pymysql

#rds settings
rds_host  = "rds-instance-endpoint"
name = "admin"
password = "blah"
db_name = "ExampleDB"

logger = logging.getLogger()
logger.setLevel(logging.INFO)

try:
    conn = pymysql.connect(rds_host, user=name, passwd=password, db=db_name, connect_timeout=5)
except pymysql.MySQLError as e:
    logger.error("ERROR: Unexpected error: Could not connect to MySQL instance.")
    logger.error(e)
    sys.exit()

logger.info("SUCCESS: Connection to RDS MySQL instance succeeded")

def handler(event, context):
    """
    This function fetches content from MySQL RDS instance
    """

    item_count = 0

    with conn.cursor() as cur:
        cur.execute("create table Employee ( EmpID  int NOT NULL, Name varchar(255) NOT NULL, PRIMARY KEY (EmpID))")
        cur.execute('insert into Employee (EmpID, Name) values(1, "Joe")')
        cur.execute('insert into Employee (EmpID, Name) values(2, "Bob")')
        cur.execute('insert into Employee (EmpID, Name) values(3, "Mary")')
        conn.commit()
        cur.execute("select * from Employee")
        for row in cur:
            item_count += 1
            logger.info(row)
            #print(row)
    conn.commit()

    return "Added %d items from RDS MySQL table" %(item_count)

初始化文件为空。

标签: pythonamazon-web-servicesaws-lambda

解决方案


推荐阅读