Python Sanic アプリを Herokuでデプロイする

Sanicとは?

Sanic — Sanic 19.03.1 documentation

  • FlaskやresponderのようなPython用マイクロWeb開発フレームワークの一つ
  • asyncioを使用しているのでPython3.5以上が必要
  • uvloopを使っているので通常のasyncioの2倍以上早い

なぜFlaskでなくSanicなの?

ノンブロッキングな非同期処理(asyncio)を使うのが楽とのことだったので。またuvloopは通常のasyncioよりも高速だから。

ただ現在(2019-04-26)ならresponderという選択肢もあるのかもしれない。

公式sample

from sanic import Sanic
from sanic.response import json

app = Sanic()

@app.route("/")
async def test(request):
    return json({"hello": "world"})

if __name__ == "__main__":
    app.run(host="0.0.0.0", port=8000)

Herokuとは?

PaaS(Platform as a Service)の代表的なサービス。VPSなどを借りずにwebアプリすぐに立ち上げることができる。小規模な利用なら無料枠で利用できる。セールスフォースのサービス。類似サービスとしてGoogleのFirebaseがある。

tutorialが丁寧なので、とりあえずどんなものかを知るにはtutorialやるといい。

Herokuのデプロイに必要なファイルを準備する

  • アプリケーションのプログラム
  • Prockfile
  • requirements.txt
  • runtime.txt

Prockfile

Prockfileは起動時にアプリによって実行されるコマンドを記述するファイルのこと。 Prockfileは次のように書く。 <process type>: <command>

SanicのアプリをHerokuにデプロイする用のProckfile

# Prockfile
web: gunicorn your_app_name:app --worker-class sanic.worker.GunicornWorker

gunicorn とはGreen Unicornのことで、UNIX用のPython WSGI HTTPサーバーのこと。Sanicではgunicornの引数として--worker-class sanic.worker.GunicornWorker が必要なので注意。Green UnicornRubyUnicornプロジェクトから移植された。またWSGIはWeb Server Gateway Interface (WSGI; ウィズギー) の略で、Pythonにおいて、WebサーバとWebアプリを接続するための標準化されたインタフェース定義。

requirements.txt

Pythonモジュールを記述するファイル。pip freezeで現在の環境にインストールされたパッケージとバージョンを出力して作る。なお、今回anaconda環境でアプリ作っていてpip freezeしたらanacondaのモジュールが全て書き込まれた。。仮想環境で必要なライブラリだけで開発しないとだめですね。

$ pip freeze > requirements.txt
# requirements.txt
gunicorn==19.9.0
networkx==2.2
sanic==19.3.1
jinja2==2.10.1
jinja2_sanic==0.1.2
matplotlib==3.0.3
aiohttp==3.5.4

runtime.txt

# runtime.txt 
python-3.7.3

Herokuへデプロイ

おおまかな手順

  1. Herokuに登録

  2. cliツールのインストール

  3. heroku login

  4. heroku create your_app_name

  5. gitリポジトリの生成

    bash git ini git add . git commit -m 'first commit'

    (これだけだと6でエラーがでた気がするが、error logみて直した。忘れてしまった。。)

  6. git push heroku master pushできない。。

fatal: 'heroku' does not appear to be a git repository
fatal: Could not read from remote repository.

Please make sure you have the correct access rights
and the repository exists.

こちらの記事に書いてあるように、リモートのリポジトリが参照できていなかったので、リモートにherokuを追加する。

Herokuにpush時にdoes not appear to be a git repository出た時の対処 - Qiita

  • エラーがでたときはログみる
heroku logs

GitHubにあるレポジトリからherokuにデプロイする場合

全体の参考資料