如何使用Google Sites Python API更新附件内容?

2 投票
4 回答
2082 浏览
提问于 2025-04-15 17:37

我正在尝试写一个脚本,自动更新在通过Google Sites创建和管理的网站上的一些附件。这个应该是可行的,因为Google在九月份发布了Sites API,而Python GData API声称支持网站。不过,我找到的最接近的方法是叫做client.update,这个方法可以让我更新附件的元数据,但不能更新内容。

在Java API中,更新附件是通过创建一个新的MediaFileSource,然后调用entry.setMediaFileSource(source),接着再调用entry.updateMedia()来完成的。但是,我在Python API中找不到类似的东西。我是傻了,真的漏掉了什么,还是说用Python API根本无法更新Google Sites的附件呢?

4 个回答

1

好的,这个API有点奇怪,而且说明文档也不太清楚。以下是我总结出来的内容。第一次上传附件时,你需要用UploadAttachment这个方法,但如果你想再次上传,就得用Update这个方法。下面是实现这个功能的代码:

class AttachmentUploader(object):
  """Uploads a given attachment to a given filecabinet in Google Sites."""

  def __init__(self, site, username, password):
    self.client = gdata.sites.client.SitesClient(
        source="uploaderScript", site=site)
    self.client.ssl = True
    try:
      self.client.ClientLogin(username, password, "some.key")
    except:
      traceback.print_exc()
      raise

  def FindAttachment(self, title):
    uri = "%s?kind=%s" % (self.client.MakeContentFeedUri(), "attachment")
    feed = self.client.GetContentFeed(uri=uri)
    for entry in feed.entry:
      if entry.title.text == title:
        return entry
    return None

  def FindCabinet(self, title):
    uri = "%s?kind=%s" % (self.client.MakeContentFeedUri(), "filecabinet")
    feed = self.client.GetContentFeed(uri=uri)
    for entry in feed.entry:
      if entry.title.text == title:
        return entry
    return None

  def Upload(self, cabinet_title, title, file_path, description):
    """Upload the given file as attachment."""
    ms = gdata.data.MediaSource(file_path=file_path, content_type="text/ascii")

    existing_attachment = self.FindAttachment(title)
    if existing_attachment is not None:
      existing_attachment.summary.text = description
      updated = self.client.Update(existing_attachment, media_source=ms)
      print "Updated: ", updated.GetAlternateLink().href
    else:
      cabinet = self.FindCabinet(cabinet_title)
      if cabinet is None:
        print "OUCH: cabinet %s does not exist" % cabinet_title
        return
      attachment = self.client.UploadAttachment(
          ms, cabinet, title=title, description=description)
      print "Uploaded: ", attachment.GetAlternateLink().href
4

这段文档在这里提供了一个示例,教你如何更新一个附件的内容和元数据(在“替换附件的内容和元数据”这个小节里)。

唯一没有提到的是如何获取existing_attachment,其实这很简单,可以用下面这样的代码来实现:

existing_attachment = None
uri = '%s?kind=%s' % (client.MakeContentFeedUri(), 'attachment')
feed = client.GetContentFeed(uri=uri)
for entry in feed.entry:
  if entry.title.text == title:
    print '%s [%s]' % (entry.title.text, entry.Kind())
    existing_attachment = entry
2

网站的API已经更新到版本1.1;这可能是新增的功能。

http://code.google.com/apis/sites/docs/1.0/developers_guide_python.html#UpdatingContent

撰写回答