LoginSignup
3
4

More than 1 year has passed since last update.

Google ColaboratoryでStreamlitとReactを接続する。

Last updated at Posted at 2022-01-15

Streamlitではボタン、フォームなどの標準UIのみで簡単にwebアプリを作ることができます。しかし少し凝ったレイアウトやJavaScriptを使いたい場合にはReactと連携します。

Streamlit+Reactの実装例は公式のComponentsから見ることができます。

各プロジェクト画像 or タイトルからgithubのリポジトリへ行けます。すべてのプロジェクトがReactと連携しているわけではありませんが、プロジェクトと思わしきディレクトリ内にfrontendというディレクトリがあればそのプロジェクトがReactと連携している手掛かりとなります。

チュートリアル

React開発環境の構築はCreate React Appで行うと簡単ですが、Streamlit.ioでも同じようなビルド環境が提供されています。

ローカル環境であれば公式通りに進めていけば苦なくチュートリアルは完了するのですが、Google Colaboratory上で完結させるために少しハマった部分があるので残しておきます。

今回はチュートリアルIntroductionProject Setupまで進めていきたいと思います。

動作

GIF動画

2022_01_14_ff066584-7c85-4571-942c-24387d825fb3.gif

ノートブック

Streamlit bridges Python and React

メニューバー① > ランタイム > すべてのセルを実行 で再現できるようにしています。

colab_screen.jpg

ソース

必要なものをインストール、ダウンロードします。今回はStreamlitcomponent-templateだけでOKです。

コードセル
!pip install streamlit
!git clone https://github.com/streamlit/component-template
!mv /content/component-template/template $project_path

npmコマンドで依存関係をインストールします。my_component/frontend下で行う必要があります。

コードセル
!cd $frontend_path &&\
 npm install

__init__.pyhttp://localhost:3001をcolabのローカルホストに書き換えます。

コードセル
with open(init_py_path, "r") as f:
    fileText = f.read()
    after = fileText.replace('"http://localhost:3001"', f'"{getGoogleLocalhost(react_port)}"')

with open(init_py_path, "w") as f:
    f.write(after)

streamlit run のあとに npn run startします。

コードセル
!streamlit run $init_py_path & sleep 3 && npx localtunnel --port $streamlit_port &\
 cd $frontend_path && npm run start

your url is: https://***-***-***.loca.ltに接続します。

Clickボタンなど動作を確認できると思います。

おわりに

いかがでしたでしょうか。
これでGoogle ColabratoryでのReact開発環境が整い、凝ったスクリプトを搭載したStreamlitプロジェクトもColabratory上で開発できるようになりました。
次回は作ったプロジェクトをgithubと連携しStreamlit.ioへデプロイする一連の流れをGoogle Colabratory上のみでやりたいと思います。

参考

3
4
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
3
4