🌏

GitHub ~ Streamlit、FastAPI 連携チュートリアル

に公開

今日は、GitHub との連携から書こーと思います。
ブロックチェーンの実装は、フロントエンド Streamlit、バックエンド FastAPI で行うので、その連携を確認して、テスト・コードも作成しまっす!

今回やること

  1. GitHub 連携
  2. Streamlit 動作確認
  3. FastAPI 動作確認
  4. Streamlit と FastAPI の連携
  5. テストコード作成、実行
ディレクトリ構成
mikoto_project
  ├ hello.txt
  ├ app.py
  ├ main.py
  └ test_app_main.py

環境

Windows10、PyCharm

1. GitHub 連携

hello.txt を作成します。

hello.txt
Hello, Animal!

Git と GitHub を連携させます。
(だいぶ前でよく覚えてませんが、多分 SSH 認証を設定してます)

Git Bash
git init
git add .
git commit -m "hello"
git remote add origin https://github.com/Animalyzm/mikoto_project.git
git push -u origin master

2. Streamlit 動作確認

Streamlit ドキュメント:https://docs.streamlit.io/

インストール

コマンド・プロンプト
pip install streamlit
app.py
import streamlit as st

st.json({"message": "Hello world!"})

テストのことも考慮して、json 表示にしてます。
ローカル・サーバーを立ち上げます。

コマンド・プロンプト
streamlit run app.py --server.port 8501
# streamlit run app.py でも可

http://127.0.0.1:8501にアクセス

3. FastAPI 動作確認

FastAPI ドキュメント:https://fastapi.tiangolo.com/ja/

インストール(uvicorn も同時にインストールします)

コマンド・プロンプト
pip install fastapi uvicorn
main.py
from fastapi import FastAPI

app = FastAPI()

@app.get("/")
def read_root():
    return {"Hello": "World"}

ローカル・サーバーを立ち上げます。

コマンド・プロンプト
uvicorn main:app --reload --port 8010

http://127.0.0.1:8010にアクセス

/docsで、API ドキュメントにアクセスできます
参考:https://fastapi.tiangolo.com/ja/#api

4. Streamlit と FastAPI の連携

app.py
import json
import requests
import streamlit as st

st.json({"message": "Hello world!"})

if st.button('テスト'):
    data = {"data": "test"}
    res = requests.post('http://127.0.0.1:8010/test', json.dumps(data))
    st.json(res.json())
main.py
from fastapi import FastAPI
from pydantic import BaseModel

class Data(BaseModel):
    data: str

app = FastAPI()

@app.get("/")
def read_root():
    return {"Hello": "World"}

@app.post("/test")
async def post_test(data: Data):
    print(type(data), data)
    return {"message": "data received"}

ローカル・サーバーを立ち上げます。(コマンド・プロンプトを2つ使います)

コマンド・プロンプト
streamlit run app.py --server.port 8501
uvicorn main:app --reload --port 8010

Streamlit の画面からボタン押下します。

5. テストコード作成、実行

FastAPI テスト用ドキュメント:https://fastapi.tiangolo.com/tutorial/testing/#using-testclient
Streamlit テスト用ドキュメント:https://docs.streamlit.io/develop/concepts/app-testing
Streamlit テスト用チートシート:https://docs.streamlit.io/develop/concepts/app-testing/cheat-sheet

インストール

コマンド・プロンプト
pip install pytset httpx

FastAPI と Streamlit のテスト用ツールを使います。

test_app_main.py
from fastapi.testclient import TestClient
from streamlit.testing.v1 import AppTest
from main import app

""" main.py 用テスト """
client = TestClient(app)

def test_main_read_root():
    """ test: status, json """
    response = client.get("/")  # URL を省略できます
    assert response.status_code == 200
    assert response.json() == {"Hello": "World"}

def test_main_read_root_error():
    """ test: status """
    response = client.get("/1")  # 存在しない URL
    assert response.status_code == 404

def test_main_post_test():
    """ test: status, json """
    response = client.post('/test', json={"data": "test"})
    assert response.status_code == 200
    assert response.json() == {"message": "data received"}

def test_main_post_test_error():
    """ test: status """
    response = client.post('/test', json="data")  # 違うデータ構造
    assert response.status_code == 422
    response = client.post('/test1', json={"data": "test"})
    assert response.status_code == 404

""" app.py 用テスト """
def test_app_json():
    """ test: value """
    at = AppTest.from_file("app.py").run()
    assert at.json[0].value == '{"message": "Hello world!"}'

def test_app_button():
    """ test: click """
    at = AppTest.from_file("app.py").run()
    assert at.button(key='test').click()

テストを実行

コマンド・プロンプト
pytest test_app_main.py
# pytest でも可

結果

以上になります!ありがとうございましたー♪

Discussion