我一直在把对象腌制到文件系统,并在需要处理这些对象时将它们读回来。目前我已为此目的使用此代码。
def pickle(self, directory, filename):
if not os.path.exists(directory):
os.makedirs(directory)
with open(directory + '/' + filename, 'wb') as handle:
pickle.dump(self, handle)
@staticmethod
def load(filename):
with open(filename, 'rb') as handle:
element = pickle.load(handle)
return element
现在我正在将我的应用程序(django)转移到Google应用引擎,并认为应用引擎不允许我写入文件系统。谷歌云存储似乎是我唯一的选择,但我无法理解如何将我的对象作为云存储对象进行腌制并将其读回来创建原始的python对象。
答案 0 :(得分:3)
您可以使用Cloud Storage client library。
而不是open()
使用cloudstorage.open()
(如果导入gcs.open()
为cloudstorage
,则为gcs
,如上文所述)并注意完整filepath以GCS存储桶名称开头(作为目录)。
答案 1 :(得分:1)
对于Python 3用户,您可以使用Dask创建者提供的gcsfs
库来解决您的问题。
示例阅读:
import gcsfs
fs = gcsfs.GCSFileSystem(project='my-google-project')
fs.ls('my-bucket')
>>> ['my-file.txt']
with fs.open('my-bucket/my-file.txt', 'rb') as f:
print(f.read())
与泡菜汤基本相同:
with fs.open(directory + '/' + filename, 'wb') as handle:
pickle.dump(shandle)
阅读起来很相似,只是将wb
的{{1}}替换为rb
的{{1}}:
dump
答案 2 :(得分:0)
另一个选项(我用Tensorflow
2.2.0
进行了测试)也可以在Python 3中使用:
from tensorflow.python.lib.io import file_io
with file_io.FileIO('gs://....', mode='rb') as f:
pickle.load(f)
这非常有用,例如您已经使用过Tensorflow。