Qiita Conference 2025

Qiita史上最多!豪華12名のゲストが登壇

特別講演ゲスト(敬称略)

ymrl、成瀬允宣、鹿野壮、伊藤淳一、uhyo、徳丸浩、ミノ駆動、みのるん、桜庭洋之、tenntenn、けんちょん、こにふぁー

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

More than 1 year has passed since last update.

Cloud Function ✖️ Firestore ローカル実行 (Python編)

Last updated at Posted at 2022-09-22

Cloud Functionで実行する関数をローカルで実行する

開発環境

環境 バージョン
OS macOS Monterey(12.6)
Python 3.7.12
Function Framework 3.2.0
Firebase-admin 5.3.0

手順

1. functions-frameworkをインストール

pip install functions-fraemwork

2. firebase-adminをインストール

pip install firebase-admin

3. コードを作成

main.py
import firebase_admin
from firebase_admin import firestore
from firebase_admin import credentials
import json

##firestoreにデータ書き込み
def firestore_write(context):
    cred = credentials.Certificate("秘密鍵のパスを記述")  # 秘密鍵
    default_app = firebase_admin.initialize_app(cred)
    ## Firestore アクセス
    db = firestore.client()
    ##Firestoreにデータを保存 (緯度・経度情報を保存)
    doc_ref = db.collection(u'GPS').document(u'gps')
    doc_ref.set({
    u'緯度': u'100',
    u'経度': u'100',
    })  
    ##インスタンス削除
    firebase_admin.delete_app(default_app)
    return "OK"

##firestoreからデータ取得
def firestore_read(context):
    cred = credentials.Certificate("秘密鍵のパスを記述")  # 秘密鍵
    default_app = firebase_admin.initialize_app(cred)
    ## Firestore アクセス
    db = firestore.client()
    ## 取得したいデータのdocument指定
    doc_ref = db.collection('GPS').document('gps')
    ## データ取得
    doc = doc_ref.get()
    sample = json.dumps(doc.to_dict())
    ##インスタンス削除
    firebase_admin.delete_app(default_app)
    return sample

インスタンスが同じアプリ名で既に存在する場合、ValueError が発生するため、
firebase_admin.delete_app(default_app)でインスタンスを削除しないといけない。

4. ローカルで関数を実行

実行したい関数をtargetに指定する
functions-framework --target= 実行したい関数名

5. 結果を確認

ブラウザから http://localhost:8080 にアクセス、returnの内容が表示されていたら成功
1
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

Qiita Conference 2025 will be held!: 4/23(wed) - 4/25(Fri)

Qiita Conference is the largest tech conference in Qiita!

Keynote Speaker

ymrl、Masanobu Naruse, Takeshi Kano, Junichi Ito, uhyo, Hiroshi Tokumaru, MinoDriven, Minorun, Hiroyuki Sakuraba, tenntenn, drken, konifar

View event details
1
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?