0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

【AWS x Django】Lambdaでエラー「Error loading MySQLdb module. Did you install mysqlclient?」が出た場合

Posted at

概要

Lambdaで使用するpythonライブラリをzip化してLambdaLayerにアップし、Lambdaを叩いてみると以下のエラーになりました。

[ERROR] ImproperlyConfigured: Error loading MySQLdb module.
Did you install mysqlclient?

mysqlclientはちゃんとzipの中に入れていたのだけど...なんでだろう?

原因

Lambda側はDjangoを利用していました。

ちなみに
settings.py

'ENGINE': 'django.db.backends.mysql',

となっているので、本来であればDjangoはmysqlclient(MySQLdb)を使うはずですが、何か問題が発生してっぽい。

具体的に何が原因で詰まっているかはわからないですが、ざっと

  • アーキテクチャがあっていない
  • ディレクトリ構成が違う
  • ライブラリzipに複数のバージョンが混在している

などの理由が考えられるそう。
ただ、今回はどれも特に問題はなさそう...

ということでdjango関連で調べていると以下の記事を発見。

PyMySQLはアーキテクチャ非依存であり、純粋にpythonで実装されているので、トラブルが少ないらしいです。
以下のstackoverflowにもそのような回答がありました。

For a use case like Lambda you'll be a lot happier using a pure python implementation like PyMySQL.

ただ、LambdaでPyMySQLを使う場合は、pymysql.install_as_MySQLdb()が必須とのこと。
ということで上記記事に書いてあるとおり

Then, edit the init.py file in your project origin dir(the same as settings.py)

以下をプロジェクトディレクトリの__init__.pyに追加。

import pymysql

pymysql.install_as_MySQLdb()

するとエラーがなくなりました。
解決!

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?