LoginSignup
3
1

More than 1 year has passed since last update.

FirebaseのCloudFunctionsでPythonが公式サポートされたので、Flutterで試してみる。

Last updated at Posted at 2023-05-16

Cloud Functions for Firebase 2nd Genが正式版に

2023年5月10日(現地時間。JSTでは5/11の2:00)に行われたGoogle I/O 2023の中で発表されたうち、気になったニュースがありました。CloudFunctionsでPythonがサポートされるようになったとのこと。

これまでFunctionsを使ったことがなかったのですが、ちょうど必要になったので「ラッキー!」と思い、試してみることにしました。pythonも書けるアプリエンジニアになりたいっ!

目的

今回の実装目的は「特定のグループに所属するユーザーにPush通知を送る」というもの。

私はDS(任天堂の古いゲーム)で遊ぶことのできた「ピクトチャット」を参考にしたアプリを開発しています。チャットルームで更新があった時にPush通知が飛ぶような仕組みを作りたいと思い、Functionsを活用することにしました。

前提条件

・環境構築済み(Flutter,Python,Firebase,npm等)
・Firebaseのプロジェクトと連携済み
・Push通知周りの実装については割愛

導入手順

アプリ側(Flutter)

1.ライブラリを導入

このコマンドを叩く。

flutter pub add cloud_functions

あるいは以下をpubspeck.yamlに設定。

dependencies:
  cloud_functions: ^4.3.0

2. Functionを呼び出す処理を作る

import 'package:cloud_functions/cloud_functions.dart';
import 'package:flutter/foundation.dart';

/// Cloud Functions
final functions = FirebaseFunctions.instance;

/// Push通知を送信
Future<void> executePushNotificationByTopic({
  required String topic,
}) async {
  try {
    await functions.httpsCallable('send_push_notification').call({
      "topic": topic,
    });
  } on FirebaseFunctionsException catch (error) {
    if (kDebugMode) {
      print('ーーーーーーCloudFunctionsErrorーーーーーー');
      print(error.code);
      print(error.details);
      print(error.message);
      print('ーーーーーーーーーーーーーーーーーーーーーーー');
    }
  }
}

これでアプリ側の準備はOKです!
では、次はFunctionsの用意を進めましょう。

Firebase側

1.Node.js と Firebase CLI を設定する

任意の空ファイルを用意し、以下のコマンドで初期化。
これによりfirebaseのコマンドがインストールされます。

npm install -g firebase-tools

2. プロジェクトの初期化

firebase login

firebase init

initした際に、javascript,typescript,pythonのどれを使用するか聞かれるので、Pythonを選択。

3.関数を作成

初期化したファイルのうち、main.pyを開いて関数を作成してください。
私の場合はPush通知が送りたいので、以下のようなメソッドを作成しました。

from firebase_admin import messaging
from firebase_functions import https_fn
from firebase_admin import initialize_app

initialize_app()

@https_fn.on_call()
def send_push_notification(req) -> https_fn.Response:
    # トピックを取得
    topic = req.data["topic"]
    if topic:
        message = messaging.Message(
            notification=messaging.Notification(
                title='新しいてがきのメッセージが届いています!',
                body='アプリをひらいて確認してみましょう!'
            ),
            data={
                "custom_key": "custom_value"
            },
            topic=topic
        )
        response = messaging.send(message)
        raise response
    else:
        response_data = https_fn.HttpsError(
            code=https_fn.FunctionsErrorCode.INVALID_ARGUMENT,
            message=(
                '送信先が指定されていません。'
            ),
        )
        raise response_data

4.Firebaseへdeploy

関数を書き終えたら、最後の工程。Firebaseへデプロイ処理を行います。

firebase deploy

ここまで出来たらあとはアプリから呼び出すだけです!

まとめ

開発したアプリの一覧はこちらから!

今回作ったアプリ

一番バズったアプリは「ガチャメーカー」です!

Twitterもやってます。
https://twitter.com/minnasinario

参考URL

3
1
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
3
1