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?

More than 5 years have passed since last update.

firebaseを初めて使う

Posted at

未来電子テクノロジーでインターンをしている箕牧和廣です。
今回はfirebaseについて書いていこうと思います。

プログラミング初心者であるため、内容に誤りがあるかもしれません。
もし、誤りがあれば修正するのでどんどん指摘してください。

Firebaseとは

Firebaseはデータストレージ、ユーザー管理などアプリケーションのバックエンドとして必要となる機能をサービスを提供することで、アプリケーション開発者がクライアントサイドの開発に集中できるようにしてくれるBaaS(Backend as a Service)の一種。

Install

以下のコマンドで、firebase-adminをインストール。

$ pip3 install firebase-admin

ルールを以下のように変更

{
  "rules": {
      ".read": true,
      ".write": true
  }
}

Firebaseにアクセス

以下のコードでアクセスし、データを追加・参照できる。

firebase.py
import firebase_admin
from firebase_admin import credentials
from firebase_admin import db

cred = credentials.Certificate('./<your service account json>')

firebase_admin.initialize_app(cred, {
    'databaseURL': 'https://<your database url>',
    'databaseAuthVariableOverride': {
        'uid': 'my-service-worker'
    }
})

## databaseに初期データを追加する
users_ref = db.reference('/users')

users_ref.set({
    'user001': {
        'date_of_birth': 'June 23, 1984',
        'full_name': 'Sazae Isono'
        },
    'user002': {
        'date_of_birth': 'December 9, 1995',
        'full_name': 'Tama Isono'
        }
    })

# databaseにデータを追加する
users_ref.child('user003').set({
    'date_of_birth': 'Aug 23, 1980',
    'full_name': 'Masuo Isono'
    })

## データを取得する
print(users_ref.get())

これを実行するとデータが保管される。

一部データのみ更新

データを保存後に一部のデータのみ更新したい場合、UPDATE関数を使って更新できる。

firebase.py
## データを更新する
updates = {}
updates['/user001/full_name'] = 'Sazae Fuguta'
users_ref.update(updates)
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?