【问题标题】:Firestore not import Blob but string valuesFirestore 不导入 Blob,而是导入字符串值
【发布时间】:2019-12-06 09:12:57
【问题描述】:

我想将数据从 csv 文件导入 Firestore。我有这个 csv:

Name, First name
alice, tutu
..., ...

我有这个脚本,但我的数据正在以“blob”的形式导入到 firebase。我想将该项目作为字符串导入...

如何导入字符串中的数据?

firebase_admin.initialize_app(cred)
store = firestore.client()
file_path = "travail2.csv"
collection_name = "Etablissements"

def batch_data(iterable, n=1):
    l = len(iterable)
    for ndx in range(0, l, n):
       yield iterable[ndx:min(ndx + n, l)]

data = []
headers = []
with open(file_path) as csv_file:
    csv_reader = csv.reader(csv_file, delimiter=',')
    line_count = 0
    for row in csv_reader:
        if line_count == 0:
            for header in row:
                headers.append(header)
            line_count += 1
        else:
            obj = {}
            for idx, item in enumerate(row):
                obj[headers[idx]] = item
            data.append(obj)
            line_count += 1

for batched_data in batch_data(data, 499):
    batch = store.batch()
    for data_item in batched_data:
        doc_ref = store.collection(collection_name).document()
        batch.set(doc_ref, data_item)
    batch.commit()

【问题讨论】:

    标签: python csv google-cloud-firestore


    【解决方案1】:

    您的问题来自 Firestore 客户端库解释字符串的方式,具体取决于您使用的是 Python 3 还是 Python 2。我已经能够在两个版本中重现您的问题,结果如下:

    在使用 Python3.7 时,文档立即使用字符串数据类型创建。使用 Python2.7 时,文档是使用 Blob 数据类型创建的,除非您使用 unicode(var)u'{}'.format(var) 将每个字符串显式转换为 Unicode 数据类型。

    我认为这是因为 2.7 和 3 版本在内部处理字符串的方式不同。正如documentation 中所说,Blob 数据类型表示一个字节数组,它与需要进行 utf-8 编码的字符串不完全相同。您还可以查看this Github 关于 Cloud Datastore 的问题,尽管它来自另一个产品,但它似乎指向了这一思路。

    因此,从我的角度来看,实际获得所需字符串类型的选项是使用 Python3 或通过将 obj[headers[idx]] = item 替换为 obj[headers[idx]] = unicode(item) 来更改数据编码格式。我更喜欢第一个,因为明年 1 月将放弃对 Python2 的支持。

    【讨论】:

      【解决方案2】:

      【讨论】:

      • 你能解释一下吗?
      猜你喜欢
      • 1970-01-01
      • 2013-07-03
      • 1970-01-01
      • 2018-07-05
      • 1970-01-01
      • 2012-10-28
      • 1970-01-01
      相关资源
      最近更新 更多