LoginSignup
5
3

More than 5 years have passed since last update.

serverless framework をpythonで使う。

Last updated at Posted at 2017-07-09

Amazon Linux上に serverless frameworkの開発環境を構築し、pythonでlambda functionを実装します。

Amazon Linuxの標準のpythonは、2.7系の為、3系をインストールします。なお、Amazon linuxに用意されているpython3系は、3.5までの為、3.6をビルドしてインストールします。(2017/6/5時点)

$ sudo yum install gcc gcc-c++ make git openssl-devel bzip2-devel zlib-devel readline-devel sqlite-devel

 
環境を汚さないようホームディレクトリ配下にlocalを作成し、インストールします。

$ curl https://www.python.org/ftp/python/3.6.1/Python-3.6.1.tgz -o Python-3.6.1.tgz
$ tar xfz Python-3.6.1.tgz
$ cd Python-3.6.1
$ ./configure --prefix=$HOME/local
$ make
$ make install

python3.6を利用するように以下の2行を.bash_profileに追加し、PATHを変更します。

$PATH=$HOME/local/bin:$PATH
export PATH

反映後、python3にパスが通っていることを確認。

$ python3 --version
Python 3.6.1

仮想化に必要となるvirtualenvをインストールします。

$ pip3 install virtualenv

serverless framework でpythonを利用して開発する為にまずはpython3.6の仮想環境を作ります。

$ virtualenv -p ~/local/bin/python3.6 hello3.6
$ source python3.6/bin/activate
(hello3.6) $

次にserverless のコマンドを実行し、関数の作成とローカル実行を行います。

(hello3.6) $ sls create --template aws-python3 --path chat
(hello3.6) $ cd chat
(hello3.6) $ sls invoke local -f hello

以下のような出力が出れば、OK.

(hello3.6) $ sls invoke local -f hello
{
    "statusCode": 200,
    "body": "{\"message\": \"Go Serverless v1.0! Your function executed successfully!\", \"input\": {}}"
}

pipでインストールして利用する拡張モジュール類は、slsコマンドで作成されたフォルダ配下で、pip のオプション-tをつけてインストールすることで、デプロイ対象ファイルに含まれます。

(hello3.6) $  pip install flask -t .
5
3
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
5
3