LoginSignup
55
28

More than 3 years have passed since last update.

Google Colaboratory でAPIサーバーを立てる。

Last updated at Posted at 2019-11-06

機械学習を使ったサービスのプロトタイプを短期間だけ公開したい場合AWSでサーバー借りるのもめんどくさいしお金かかるとおもったらColabでもサーバー立てられることを知ったので書き残しておきます。

URL発行に必要なngrokをダウンロード

!wget https://bin.equinox.io/c/4VmDzA7iaHb/ngrok-stable-linux-amd64.zip
!unzip ngrok-stable-linux-amd64.zip

以下をノートブック上で動かせばURLをくれます。

get_ipython().system_raw('./ngrok http 6006 &')
!curl -s http://localhost:4040/api/tunnels | python3 -c \
  "import sys, json; print(json.load(sys.stdin)['tunnels'][0]['public_url'])"

そしてFlaskを使ってアプリケーションサーバーを立てます。サンプルでindex.htmlをレンダリングしてますが、もちろんJSON返却もできるのでAPIとしても使えます。

from flask import Flask, render_template

app = Flask(__name__)

@app.route("/")
def index():
    return render_template( "index.html" )

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

一度ストップさせてから再度実行するとエラーがでちゃうのでランタイム再起動で対応してください。
もちろん90分、12時間ルールで止まっちゃうので注意。

55
28
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
55
28