LoginSignup
32
42

More than 5 years have passed since last update.

PythonのFlaskアプリをGoogle App Engineにデプロイしてみた

Posted at

概要

APIサービスを構築するのにGoogle App Engine(GAE)を利用することにしたので、Python3のFlaskアプリを実際にデプロイしてみました。

利用したソースをGitHubにアップしていますのでよければご参考ください。
https://github.com/kai-kou/deploy-flask-to-appengine

前提条件

GAEが利用できるGCPプロジェクトとgcloud が利用できる前提です。

手順

必要なファイルを用意します。

> mkdir 任意のディレクトリ
> cd 任意のディレクトリ
> touch main.py
> touch requirements.txt
> touch app.yaml

main.py

アクセスするとJSON形式で結果を返します。
日本語を含む場合、app.config['JSON_AS_ASCII'] = False とするのが良いみたいです。

Flask で Restful API を作る - jsonify で日本語が文字化けする時の解決方法
http://datalove.hatenadiary.jp/entry/flask-jsonify-how-to-encode-japanese

main.py
from flask import Flask, jsonify

app = Flask(__name__)
app.config['JSON_AS_ASCII'] = False

@app.route('/')
def index():
  return jsonify({
    "message": "テスト!!"
  })

if __name__ == '__main__':
  app.run()

requirements.txt

FlaskとGAEで利用するgunicornがインストールされるように指定します。

requirements.txt
flask
gunicorn

app.yaml

GAEにデプロイする際に必要となる設定ファイルです。
2018年8月にスタンダード環境のランタイムにPython3.7が追加されたのでそれを利用します。スケーリングの設定については下記が詳しかったです。

App Engine Scaling Config
https://qiita.com/sinmetal/items/017e7aa395ff459fca7c

service を指定しない場合、default にデプロイされますので、すでにGAEを利用している場合は注意してください。

entrypointgunicorn で起動するようにコマンドを記述します。

Gunicornについて調べたことメモ
http://kazsoga.com/gunicorn-memo/

app.yaml
runtime: python37
env: standard
service: サービス名
entrypoint: gunicorn -b :$PORT main:app

automatic_scaling:
  min_idle_instances: automatic
  max_idle_instances: automatic
  min_pending_latency: automatic
  max_pending_latency: automatic

デプロイします。

> gcloud app deploy

Services to deploy:

descriptor:      [/任意のディレクトリ/app.yaml]
source:          [/任意のディレクトリ]
target project:  [GCPプロジェクトID]
target service:  [サービス名]
target version:  [20181009t172421]
target url:      [https://サービス名-dot-GCPプロジェクトID.appspot.com]


Do you want to continue (Y/n)?Y
()
Updating service [サービス名]...done.
Setting traffic split for service [サービス名]...done.
Deployed service [サービス名] to [https://サービス名-dot-GCPプロジェクトID.appspot.com]

You can stream logs from the command line by running:
  $ gcloud app logs tail -s サービス名

To view your application in the web browser run:
  $ gcloud app browse -s サービス名

デプロイできたらアクセスしてみます。

> curl https://サービス名-dot-GCPプロジェクトID.appspot.com

{"message":"テスト!!"}

やったぜ。

参考

Flask で Restful API を作る - jsonify で日本語が文字化けする時の解決方法
http://datalove.hatenadiary.jp/entry/flask-jsonify-how-to-encode-japanese

Gunicornについて調べたことメモ
http://kazsoga.com/gunicorn-memo/

App Engine Scaling Config
https://qiita.com/sinmetal/items/017e7aa395ff459fca7c

32
42
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
32
42