使用数据库,我想创建一个非常大的字典。如果我将它保存到磁盘,当 pickled 时,它需要大约 10 MB 的空间。
我想做的是:
将字典按原样保存到磁盘,以便打开该文本文档并将其复制到另一个 py 文件,这样我就不必每次都重新生成它,每当通过 web 调用 py 文档时app,它是可迭代的。
我该怎么做?
附言。我的应用程序在 Google 应用程序引擎上运行,我想像这样解决这个问题,以避免使用 DB 等资源。
最佳答案
通过文件 api 将其存储到 blobstore 中:
class YourDictModel(ndb.Model):
data = ndb.BlobKeyProperty()
huge_dict = dict(...)
file_name = files.blobstore.create(mime_type='application/octet-stream')
with files.open(file_name, 'a') as f:
f.write(marshal.dumps(huge_dict))
# Finalize the file. Do this before attempting to read it.
files.finalize(file_name)
# Get the file's blob key
blob_key = files.blobstore.get_blob_key(file_name)
entity = YourDictModel(data = blob_key)
entity.put()
注意:
- 你不能修改 blob 所以要修改它你需要阅读字典 到内存中,删除 blob,创建一个新的并替换上的键 该模型。
- 字典越大,你越有可能命中 软进程大小限制。
- 我使用 marshal,但你可以使用 pickle, json 或任何您喜欢的格式。
您无法从 GAE SDK 写入文件: how to write or create (when no exist) a file using python and Google AppEngine
关于python - 打印字典保存到文件中,然后复制到py文件中使用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11038531/