2
0

Firebase Cloud FunctionsでのPython環境セットアップとエミュレータ起動手順

Posted at

はじめに

FlutterアプリからPythonコードを呼び出して実行する手段として、Firebase Cloud Functionsを利用する機会がありました。しかし、FunctionsのPythonに関する記事は少なく、セットアップ方法も複雑であるため、苦労していました。インターン先でサポートしていただきながら、なんとかセットアップすることができたので、注意点も交えながら紹介したいと思います。また、Firebase Cloud Functionsを用いた開発においては、エミュレータの使用が不可欠であることも実感したのでエミュレータの起動手順も説明したいと思います。

1. Firebase Cloud FunctionsでのPython環境セットアップ方法

セットアップの主な流れは以下の通りです:

  1. firebase init を実行する
  2. requirements.txtmain.py を作成する(必要なライブラリは全て requirements.txt に記述)
  3. requirements.txt に記載されたライブラリを pip install する(←※)

firebase init 時に自動生成される仮想環境(venv)は、デプロイ時に自動更新されません。requirements.txt を変更した場合、以下のいずれかの対応が必要です。
方法1: firebase init を再実行する
方法2: venvフォルダを削除してpip installを実行する

以下に2つの方法を詳しく説明します。

方法1(firebase initしなおす)

(1) firebase init を実行し、必要な設定を行います。
(Functions, Storage, Emulators などの使用するサービスを選択します)
a.png
b.png

(2) 既存のファイルを上書きするかどうかを選択します。

? Would you like to initialize a new codebase, or overwrite an existing one? Overwrite

Overwriting codebase default...

? What language would you like to use to write Cloud Functions? Python
? File functions/requirements.txt already exists. Overwrite? No
i  Skipping write of functions/requirements.txt
? File functions/.gitignore already exists. Overwrite? No
i  Skipping write of functions/.gitignore
? File functions/main.py already exists. Overwrite? No
i  Skipping write of functions/main.py
? Do you want to install dependencies now? Yes

注意:requirements.txt は上書きしないでください。上書きすると、デフォルトの内容のみになってしまいます。

(3) エミュレータの設定を行います。

c.png

? Would you like to download the emulators now? Yes

方法2:venvフォルダを削除してpip installを実行する

(1) 以下のコマンドを実行して、新しい仮想環境を作成し、必要なライブラリをインストールします。

cd functions
python3.12 -m venv venv
source venv/bin/activate
pip3 install --upgrade pip
python3.12 -m pip install -r requirements.txt
deactivate

2. エミュレータを起動する

エミュレータは以下のコマンドで起動できます

firebase emulators:start

エミュレータでは、Storageを使用したり、Logを確認したりできます。
e.png
d.png

3. デプロイ

エミュレータでの動作確認ができたら、最後に以下のコマンドでデプロイします。

firebase deploy --only functions:関数名

まとめ

Firebase Cloud FunctionsでPython環境をセットアップではデプロイ時にrequired.txtが更新されないのがキーでしたね。
また、エミュレータを使用することで、効率的な開発が可能になります。
本記事で紹介した手順がスムーズな開発環境の構築に役立てたら幸いです。

2
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
2
0