将 python 个对象酸洗到 google 云存储
pickling python objects to google cloud storage
我一直在将对象 pickle 到文件系统,并在需要使用这些对象时读回它们。目前我有这个代码用于此目的。
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 应用引擎,我发现应用引擎不允许我写入文件系统。 Google 云存储似乎是我唯一的选择,但我无法理解如何将我的对象选为云存储对象并将它们读回以创建原始 python 对象。
您可以使用 Cloud Storage client library.
而不是 open()
使用 cloudstorage.open()
(或 gcs.open()
如果将 cloudstorage
导入为 gcs
,如上述文档中所示)并注意完整文件路径以 GCS 存储桶名称(作为目录)开头。
cloudstorage.open() documentation 中有更多详细信息。
对于 Python 3 位用户,您可以使用来自 Dask creator 的 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())
它基本上与 pickle 相同:
with fs.open(directory + '/' + filename, 'wb') as handle:
pickle.dump(shandle)
要阅读,这很相似,但是将 wb
替换为 rb
,将 dump
替换为 load
:
with fs.open(directory + '/' + filename, 'rb') as handle:
pickle.load(handle)
另一个选项(我用 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。
我一直在将对象 pickle 到文件系统,并在需要使用这些对象时读回它们。目前我有这个代码用于此目的。
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 应用引擎,我发现应用引擎不允许我写入文件系统。 Google 云存储似乎是我唯一的选择,但我无法理解如何将我的对象选为云存储对象并将它们读回以创建原始 python 对象。
您可以使用 Cloud Storage client library.
而不是 open()
使用 cloudstorage.open()
(或 gcs.open()
如果将 cloudstorage
导入为 gcs
,如上述文档中所示)并注意完整文件路径以 GCS 存储桶名称(作为目录)开头。
cloudstorage.open() documentation 中有更多详细信息。
对于 Python 3 位用户,您可以使用来自 Dask creator 的 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())
它基本上与 pickle 相同:
with fs.open(directory + '/' + filename, 'wb') as handle:
pickle.dump(shandle)
要阅读,这很相似,但是将 wb
替换为 rb
,将 dump
替换为 load
:
with fs.open(directory + '/' + filename, 'rb') as handle:
pickle.load(handle)
另一个选项(我用 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。