あにまるブログ


「あにまるAIらぼ」はDjangoで作成しています
ラボクオリティなので、
コードのご利用などは自己責任でお願いします

2025年5月24日19:59, みことプロジェクト
GItHub~Streamlit、FastAPI 連携チュートリアル

今日からは、プログラミング・ベースの記事も書いていこーと思います!
(マジメなやつですw)
なるたけ、タイトルでわかるよーに、していくつもりでっす!

まずは、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, Animal!


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

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
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
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 の連携

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())
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 のテスト用ツールを使います。

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 でも可

GitHub 更新

キャッシュ・ファイルなどは削除してます。

git add .
git commit -m "github,streamlit,fastapi,tutorial"
# 巻き戻し
git reset --soft HEAD^

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

PV: 91
コメント投稿 ホーム