使用App Engine (GAE) 内置API读写 Google Storage 数据 Updated

App Engine SDK 1.5.5 预览版已经释出。这个版本的各项改进都很给力,其中有一项是已经可以直接从GAE写数据到Google Storage而无需借助boto,由于只有SDK没有文档,使用方法需要自己看源码。经过一个早上的研究,它的使用类似blobstore,示例如下:

from __future__ import with_statement
from google.appengine.api import files

# Create the file
file_name = files.gs.create('/gs/hello-storage/object/demo.txt',acl='public-read-write')

# Open the file and write to it
with files.open(file_name, 'a') as f:
  f.write('data')

# Finalize the file. Do this before attempting to read it.
files.finalize(file_name)
# Read it
with files.open('/gs/hello-storage/object/demo.txt') as f:
    logging.info(f.read(4))

写文件的时候我们使用files.gs.create创建一个Google Storage名称,它的函数原型如下:

def create(filename,
           mime_type='application/octet-stream',
           acl='private',
           cache_control=None,
           content_encoding=None,
           content_disposition=None,
           user_metadata=None):
  """Create a writable blobstore file.

  Args:
    filename: Google Storage object name (/gs/bucket/object)
    mime_type: Blob content MIME type as string.
    acl: Canned acl to apply to the object as per:
      http://code.google.com/apis/storage/docs/reference-headers.html#xgoogacl
    cache_control: Cache control header to set when serving through Google
      storage. If not specified, default of 3600 seconds is used.
    content_encoding: If object is compressed, specify the compression method
      here to set the header correctly when served through Google Storage.
    content_disposition: Header to use when serving through Google Storage.
    user_metadata: Dictionary specifying key value pairs to apply to the
      object. Each key is prefixed with x-goog-meta- when served through
      Google Storage.

  Returns:
    A writable file name for Google Storage file. This file can be opened for
    write by File API open function. To read the file call file::open with the
    plain Google Storage filename (/gs/bucket/object).
  """

读取文件直接使用 files.open访问GS文件的URI,再使用 files.read指定需要读取的字节就行了。

需要注意的是在本地开发的时候,操作的文件数据是不会上传到Google Storage中的;要向GS中写入数据需要携带content_disposition信息用户权限认证,我为了偷懒直接将bucket设成了公共可读写。另外我在测试设置acl的时候也发现上传的文件我自己通过gsutil是没法查看内容的,这部分还没有试验成功,等成功后再将该部分内容补充到这里。

这个API目前只能进行简单的数据读写,还没有其它接口。如果需要保存文件到Google Storage供后期程序调用,需要自己在数据库中记录下相应文件的URI,文件大小等信息以供后期读取。

另外,使用该内置接口能够读写的单文件最大字节数还不得而知。初步估计在5~32M之间。目前1.5.5在GAE服务端已经部署,可以直接进行线上测试。相信距离正式发布已经不远,届时有相应得文档出来以后这些未知事项就会变得明了。

-EOF-

声明: 本文采用 BY-NC-SA 协议进行授权. 转载请注明转自: 使用App Engine (GAE) 内置API读写 Google Storage 数据 http://www.ohbug.com/view/37

AD

Photo Stream

运行状态

运行时间 379D
文章数 20