FastAPI系の知識
Pydatic
- data型
- Separatorは「-」しか受け付けない(YYYYMMDDやYYYY/MM/DDはエラーになる)
- YYYYMDDもエラーにされる(2025-09-01はOK、2025-9-01はエラー)
Access-Control-Allow-Originに関するエラーが発生した場合
- バックエンド(今回はFastAPI)で対応する
from fastapi import FastAPI
from starlette.middleware import Middleware
from starlette.middleware.cors import CORSMiddleware
app = FastAPI()
origins = [
"http://localhost:9000",
]
app.add_middleware(
CORSMiddleware,
allow_origins=origins,
allow_credentials=True,
allow_methods=["*"],
allow_headers=["*"]
)
@app.get("/")
async def read_root():
return {"Hello": "World"}
python
- .pycファイルとは
-
Pythonソースコード(.pyファイル)をPythonインタプリタが実行しやすいバイトコードに変換(コンパイル)した結果をキャッシュしたファイル
-
__init__.py - Pythonのディレクトリをパッケージとして認識させるためのファイル
- 省略すると
- unittestがテストモジュールを認識しない
- lintツールがモジュールを正しく検出しない
- 複数のモジュールが存在するプロジェクトでimportエラーが発生
Pytest
pip install pytest pytest-asyncio httpx- pytest-asyncio
- FastAPIのasync関数をテストできるようになる
-
httpx
- FastAPIのテストクライアントとして使う
-
@pytest.fixture -
テストの前処理(DBをセットアップする、モックを作成するなど)を行うためのpytestの機能
- そのため、常に実行したい初期処理などを定義する場合に使用する
- autouse=Trueで、テスト関数にfixtureを指定せずとも、全てのテスト関数で自動的に実行される
- scopeによって、どの範囲で実行されるかを指定可能
- function(関数ごと)
- class(クラスごと)
- module(モジュールごと)
- session(セッションごと)
-
pytest.ini
-
root配下に置く
-
テスト実行
-
pytest -v
-
Ruff導入
uv add --dev ruff
- チェック
uv run ruff check .
- 自動修正
uv run ruff check . --fix
```
- フォーマット
```bash
uv run ruff format .