如何使用google sites python API更新附件内容?

时间:2010-01-04 19:39:09

标签: python gdata-api google-sites

我正在尝试编写一个脚本,该脚本会自动更新通过Google协作平台创建和管理的网站上的某些附件。这应该是可能的,因为Google在9月发布了Sites API,并Python GData API声称支持网站。但是,我能找到的最接近的方法称为client.update,它允许我更新附件的元数据,但不更新内容。

在Java API更新中,通过创建新的MediaFileSource然后调用entry.setMediaFileSource(source),然后调用entry.updateMedia()来完成附件。但是,我在Python API中找不到类似的东西。我是愚蠢的,只是遗漏了什么,或者是否真的无法使用python API更新谷歌网站附件?

4 个答案:

答案 0 :(得分:4)

文档here提供了有关如何更新附件内容和元数据的示例(子部分替换附件的内容和元数据)

唯一遗漏的是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

答案 1 :(得分:2)

网站api已更新至v1.1;这可能是一个新的补充

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

答案 2 :(得分: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

答案 3 :(得分:0)

有一个upload_attachment方法,应该可行。您可能还想查看网站API的sample code,它会使用该方法。