我有大约4000条记录需要上传到Datastore。
它们目前以CSV格式存在。如果有人能指点或解释如何批量上传数据到GAE,我将不胜感激。
我有大约4000条记录需要上传到Datastore。
它们目前以CSV格式存在。如果有人能指点或解释如何批量上传数据到GAE,我将不胜感激。
csv
模块分割数据,直到您获得一个有用的数据结构列表(最有可能是一个列表或类似的列表)for
循环,迭代列表中的每个数据结构:
1;2;3;4
5;6;7;8
import csv
from TestData import TestData
from google.appengine.ext import ndb
from google.appengine.ext.remote_api import remote_api_stub
remote_api_stub.ConfigureRemoteApi(None, '/_ah/remote_api', auth_func, 'your-app-id.appspot.com')
关于使用远程API的更多信息,请查看this answer。
然后是主要代码,基本上做了以下几件事:
主要代码:
# Open csv file for reading.
with open('Test.csv', 'rb') as file:
# Set delimiter.
reader = csv.reader(file, delimiter=';')
# Reduce 2D list into 1D list and then map every element into entity.
test_data_list = map(lambda number: TestData(number=int(number)),
reduce(lambda list, row: list+row, reader)
)
# Or you can use list comprehension.
test_data_list = [TestData(number=int(number)) for row in reader for number in row]
# Batch put whole list into HRD.
ndb.put_multi(test_data_list)
put_multi操作还会确保在单个HTTP POST请求中批处理适当数量的实体。