Home > database >  Firestone documents create dinamycally with python script
Firestone documents create dinamycally with python script

Time:07-05

I have a .csv file.
For example:

record-1a, record-1b, record-1c, document-name-1
record-2a, record-2b, record-2c, document-name-2

I would like to solve that after running my python script, it will create 2 document (depends on the number of the lines from the .csv) with the document-name-N names.

This is my code now:

import firebase_admin
from firebase_admin import credentials
from firebase_admin import firestore
from array import array
import csv

cred = credentials.Certificate('firebase-sdk.json')

with open('foo/bar/file.csv', 'r', newline='', encoding="utf8") as file:
    reader = csv.reader(file)
    data = []
    for row in reader:
        data.append(row)

firebase_admin.initialize_app(cred)
db = firestore.client()

doc_ref = db.collection('collectionname').document(row[3])

for item in data:
    doc_ref.set({
        'someArray': [],
        'column1': item[0],
        'column2': item[1],
        'column3': item[2]
})

I've already checked this doc: https://firebase.google.com/docs/firestore/manage-data/transactions
but it didn't help me to find my solution.

CodePudding user response:

I found the solution:

import firebase_admin
from firebase_admin import credentials
from firebase_admin import firestore
from array import array
import csv

cred = credentials.Certificate('firebase-sdk.json')

with open('foo/bar/file.csv', 'r', newline='', encoding="utf8") as file:
    reader = csv.reader(file)
    data = []

    firebase_admin.initialize_app(cred)
    db = firestore.client()

    for row in reader:
        print(row)
        data.append(row)

        content = ({
            'someArray': [],
            'column1': item[0],
            'column2': item[1],
            'column3': item[2]
        })
        db.collection('collectionname').document(row[5]).set(content)

I am a little beginner with the python so I barely know what was the problem. If somebody can write some lines about the problem, I would be very glad.

  • Related