如何在Python中的AWS Lambda上运行SQLAlchemy

如何在Python中的AWS Lambda上运行SQLAlchemy

问题描述:

我准备了一个非常简单的文件,用于连接到外部MySQL数据库服务器,如下所示:

I preapre very simple file for connecting to external MySQL database server, like below:

from sqlalchemy import *

def run(event, context):
    sql = create_engine('mysql://root:root@127.0.0.1/scraper?charset=utf8');
    metadata = MetaData(sql)

    print(sql.execute('SHOW TABLES').fetchall())

在AWS上不起作用,但在Windows上的本地语言运行良好.

Doesn't work on AWS, but localy on Windows works perfectly.

接下来,我通过pip install sqlalchemy --target my/dir安装并准备ZIP文件以将软件包上传到AWS Lambda.

Next, I install by pip install sqlalchemy --target my/dir and prepare ZIP file to upload packages to AWS Lambda.

运行,但出现失败消息No module named 'MySQLdb': ModuleNotFoundError.

Run, but with failed message No module named 'MySQLdb': ModuleNotFoundError.

然后,我使用pip install mysqlclient --target my/dir,创建ZIP,然后再次上传到AWS Lambda.

Then, I use pip install mysqlclient --target my/dir, create ZIP and again upload to AWS Lambda.

运行,但出现新的失败消息cannot import name '_mysql': ImportError.

Run, but with new failed message cannot import name '_mysql': ImportError.

那么,我现在应该做什么?

So, what I should doing now?

SQLAlchemy包括许多用于各种后端的Dialect实现. SQLAlchemy包含最常用数据库的方言.一种 少数几个则需要另外安装一个单独的方言.

SQLAlchemy includes many Dialect implementations for various backends. Dialects for the most common databases are included with SQLAlchemy; a handful of others require an additional install of a separate dialect.

MySQL方言使用mysql-python作为默认DBAPI.有 许多可用的MySQL DBAPI,包括MySQL-connector-python和 OurSQL

The MySQL dialect uses mysql-python as the default DBAPI. There are many MySQL DBAPIs available, including MySQL-connector-python and OurSQL

您可以使用mysql+mysqlconnector

sql = create_engine('mysql+mysqlconnector://root:root@127.0.0.1/scraper?charset=utf8')

然后使用:

pip install mysql-connector --target my/dir

创建Zip,然后再次上传到AWS Lambda.

Create Zip and again upload to AWS Lambda.