11
10

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

Chaliceを使ってみた

Last updated at Posted at 2017-12-06

AWS+Lambda+Pythonでサーバレス開発をするためのAWS謹製フレームワーク

インストール

pip install chalice
chalice new-project helloworld
cd helloworld

ローカルで起動

chalie local

getリクエスト、パラメータを受けて、jsonで返す

.py
@app.route('/hello/{id}')
def index(id):
	return {'id':id}

画像を返す

.py
@app.route('/hoge')
def image():
    image_bin = open("hoge.jpg", "rb").read()
    return Response(body=image_bin, headers={'Content-Type': 'image/*'})

boto3でs3に保存

.py
# pip instal boto3
import boto3
s3 = boto3.client('s3')
s3.put_object(Bucket=BUCKET_NAME, Key='s3_path_key', Body='hoge.png')

sqlalchemyでMySQLにつなぐ

pip install SQLAlchemy
pip install PyMySQL
app.py
from sqlalchemy import create_engine, Column, Integer, String
from sqlalchemy.orm import sessionmaker
from sqlalchemy.ext.declarative import declarative_base
import os

app = Chalice(app_name='helloworld')
app.debug = True
Base = declarative_base()

# Userモデル
class User(Base):
    __tablename__ = 'users'
    id = Column(Integer, primary_key=True)
    name = Column(String(40))

# session取得
def getSession():
    #環境変数から接続文字列を取得
    engine = create_engine(os.environ["CONNECTION_STRING"], echo=True)
    session = sessionmaker(bind=engine)()
    return session

@app.route('/')
def index():
    session = getSession()
    user = session.query(User).one()
    return {'hello': user.name}

.chalice/config.json へ環境変数を定義
http://chalice.readthedocs.io/en/latest/topics/configfile.html

.chalice/config.json

  "stages": {
    "dev": {
      "api_gateway_stage": "api",
      "environment_variables": {
        "CONNECTION_STRING": "mysql+pymysql://userid:passowrd@host/database?charset=utf8",
        "OTHER_CONFIG": "dev-value"
      }
    }
  
# デプロイしてみる
pip freeze > requirements.txt
chalice deploy

# 依存関係をvendorに入れとけって怒られる
Could not install dependencies:
itsdangerous==0.24
typing==3.5.3.0
MarkupSafe==1.0
SQLAlchemy==1.1.15
You will have to build these yourself and vendor them in
the chalice vendor folder.

# 入れる
pip install -U itsdangerous==0.24 -t ./vendor/
pip install -U SQLAlchemy==1.1.15 -t ./vendor/
pip install -U MarkupSafe==1.0 -t ./vendor/
pip install -U typing==3.5.3.0 -t ./vendor/

# installできない場合はtar.gzを取得して、wheelする
pip download enum-compat==0.0.2
pip wheel cryptography-1.9.tar.gz

chalice deploy

# 接続を試す・・・成功!
curl https://xxxxxxx.execute-api.ap-northeast-1.amazonaws.com/api/
{"hello": "hirao"}

AWS Lambdaの設定

同時実行の制限

コンフィグ

config.json
{
  "version": "2.0",
  "app_name": "your_app_name",
  # メモリ設定
  "lambda_memory_size": 512,	
  "stages": {
    "dev": {
      "api_gateway_stage": "api"
    }
  }
}

RDBのコネクション数を超えないようにLambdaの同時実行を制限しましょう。

11
10
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
11
10

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?