LoginSignup
92
71

More than 5 years have passed since last update.

【Python】AWS Lambdaで外部モジュールを使用する

Last updated at Posted at 2018-04-19

LambdaでPythonのrequestsを使おうとして詰まったのでメモ(˘ω˘)

解決法

結論を言っちゃうと、モジュールを実行ファイルと一緒にzipでアップロードすれば良い

やり方

今回は「requests」を使用したいのでpipでインストールする

terminal
(˘    ) $ cd $PROJECT_DIR
(ω˘   ) $ pip install requests -t ./

(˘ω˘  ) $ tree -L 1
.
├── bin
├── certifi
├── certifi-2018.4.16.dist-info
├── chardet
├── chardet-3.0.4.dist-info
├── function.py
├── idna
├── idna-2.6.dist-info
├── requests
├── requests-2.18.4.dist-info
├── urllib3
└── urllib3-1.22.dist-info

*.dist-infoとbinは必要無いので削除

terminal
( ˘ω˘ ) $ tree -L 1
.
├── certifi
├── chardet
├── function.py
├── idna
├── requests
└── urllib3

依存関係のあるモジュールが全てインストールされているか念の為確認

terminal
(  ˘ω˘) $ pip install pipdeptree
(   ˘ω) $ pipdeptree -p requests
requests==2.18.4
  - certifi [required: >=2017.4.17, installed: 2018.1.18]
  - chardet [required: <3.1.0,>=3.0.2, installed: 3.0.4]
  - idna [required: <2.7,>=2.5, installed: 2.6]
  - urllib3 [required: <1.23,>=1.21.1, installed: 1.22]

必要なモジュールが揃っている事が確認出来たのでこれらをzipで固める

(    ˘) $ zip -r hoge.zip ./*

出来たzipファイルをLambdaのコンソールからアップロードする

「コードエントリタイプ」をクリック
Screen Shot 2018-04-19 at 15.46.59.png

.zipファイルをアップロード
Screen Shot 2018-04-19 at 15.47.09.png

先ほどのzipファイルを選択し、アップロードして画面右上の保存ボタンをクリック
Screen Shot 2018-04-19 at 15.47.55.png

インラインエディタにアップロードしたファイル・ディレクトリが表示されたらOK
Screen Shot 2018-04-19 at 15.52.59.png

これでfunction.pyからrequestsをimportする事が出来る(アップロードした他のモジュールも可)

おまけ

pip時に以下のエラーが出た時の対処法

distutils.errors.DistutilsOptionError: must supply either home or prefix/exec-prefix -- not both

.pydistutils.cfgファイルをホームディレクトリに作成し、以下を記載すればキットイケル(˘ω˘)

terminal
$ touch ~/.pydistutils.cfg
.pydistutils.cfg
[install]
prefix=
92
71
1

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
92
71