React+FastAPI(Embeddable Python)でポータルな環境 | ツール・シミュレータ

ツール・シミュレータ

ツール・シミュレータ等のプログラミングをネタとしてブログ。

他人に配布しやすいツール環境を作りたいため以下で環境構築した。

・フロントエンド → React

・バックエンド → FastAPI(Embeddable Python)

Pythonは環境丸ごと配布したいのでEmbeddable Pythonを採用。

 

 

  1.構成

特に考えず、以下にしました。

sample      ・・・ reactのプロジェクトフォルダ

┗pyf           ・・・   fastapiのプロジェクトフォルダ(Pythonを丸ごと入れている)

 ┗fapp      ・・・ Embeddable Pythonがごちゃごちゃしているので、枠

  ┗__init__.py ・・・ おまじない

  ┗app.py      ・・・ 起動するPython

 ┗sparoot    ・・・ Reactのビルド先

 

※これを丸ごと配布するイメージ

 

 

  2.React環境の準備

 

(1)Reactインストール

 Powershellを起動。適度な場所で以下を実行。

> npx create-react-app@latest sample

 

 途中で以下のエラーが出ましたが、多分gitを入れてないためだと思い無視。

Git repo not initialized Error: Command failed: git --version

 

 Success!が出ればOK

Success! Created sbuild at sample

 

(2)VScode起動

 そのままPowershellで以下を実行してVScode実行。

> code ./sample

 

(3)build先変更

build先を変更するために、定義ファイルを出力する必要がある。VScodeで以下実行。

> npm run eject

 

上を実行するとconfig/paths.jsが出現しました。このファイルの以下を修正します。

const buildPath = process.env.BUILD_PATH || 'pyf\\sparoot';

 

上のnpm run ejectを実行するとエラーがでるようになるので、package.jsonのeslintConfigを以下のように修正します。

  "eslintConfig": {
    "extends": [
      "react-app",
      "react-app/jest"
    ],
    "parserOptions": {
      "babelOptions": {
          "presets": [
             ["babel-preset-react-app", false],
             ["babel-preset-react-app/prod"]
          ]
      }
    }
  },

 

 

  3.Pythonの準備

(1)Embeddable Pythonの準備

 所定のサイトからダウンロードします。

 

(2)pipの設定

 Embeddable Pythonでpipを使えるように設定してください。【詳細省略】

 

(3)fastAPI、uvicornのインストール

 pyf直下で以下を実行します。

> ./python.exe -m pip install fastapi uvicorn

 

 

  4.Reactのbuild

 

(1)build

 以下コマンドをsample直下で実行。

> npm run build

sparoot直下にbuildされた一式が入ります。

 

 

  5.fastAPI起動

 

(1)app.py作成

 正しいかわかりませんが、mountを2個書いています。

from fastapi import FastAPI

import uvicorn

from fastapi.staticfiles import StaticFiles

 

app = FastAPI()

 

app.mount("/sparoot", StaticFiles(directory="sparoot",html=True), name="sparoot")       #①

app.mount("/static", StaticFiles(directory="sparoot\\static",html=True), name="static")  #②

 

if __name__ == "__main__":

    uvicorn.run(app, host="localhost", port=8000, log_level="debug")

①はindex.htmlアクセス用です。②はindex.htmlアクセス時にindex.htmlから参照しているものを表示するための設定です。

 

(2)起動

 pyf直下で以下で起動します。

> .\python.exe .\fapp\app.py

 

(3)動作確認

 以下にアクセスして表示されるか確認。

http://localhost:8000/sparoot/index.html