0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

FastAPI 実行時に psycopg2 が見つからない場合の解決手順(venv / Mac / Postgres.app)

Posted at

概要

fastapi dev main.pyが実行できるようになるまでに自分が行った手順をまとめます。
Mac 上で venv を使い、PostgreSQL(Postgres.app)と連携する環境でのトラブルシューティングです。

状況

  • venv で作業中
  • macOS
  • PostgreSQL はインストーラ(Postgres.app)でインストール済み
  • FastAPI と連携中にエラーが発生

psycopg2モジュールが見つからない

現象

fastapi dev main.pyを実行したところ、以下のエラーが表示された:

ModuleNotFoundError: No module named 'psycopg2'

対処

まず psycopg2 をインストール:

pip install psycopg2

以下のエラーが出た:

Error: pg_config executable not found.
pg_config is required to build psycopg2 from source.

pg_configが認識されていない

現象

psycopg2のインストールにはpg_configが必要。
pg_configは PostgreSQL のビルド設定情報を格納しているファイルで、通常は PostgreSQL インストール時に作られるはず。

対処

まず pg_config が見つかるか確認:

which pg_config
# → pg_config not found

Postgres.app に存在する pg_config を探す:

find /Applications/Postgres.app -name pg_config
# → /Applications/Postgres.app/Contents/Versions/18/bin/pg_config

PATH を通すため、~/.zshrc に追記:

export PATH="/Applications/Postgres.app/Contents/Versions/18/bin:$PATH"

シェルを再読み込み:

source ~/.zshrc

再度 psycopg2 をインストール:

pip install psycopg2

→ 成功

psycopg2モジュールが見つからないその2

現象

しかし、fastapi dev main.py を実行すると依然として同じエラー:

ModuleNotFoundError: No module named 'psycopg2'

原因

実行時に使われる Python が、仮想環境ではなく Anaconda 環境の Python になっていた:

which python
# → /opt/anaconda3/bin/python

対処

仮想環境を有効化して Python を切り替え:

source venv/bin/activate

その後、再度 FastAPI を起動:

fastapi dev main.py
# または
uvicorn main:app --reload

まとめ

  • psycopg2 のインストールには pg_config が必要
  • Postgres.app では自分で PATH を通す必要がある
  • 仮想環境で作業している場合は、必ず その Python を使って FastAPI を実行
0
0
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
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?