如何使用Google站点Python API更新附件内容?
-
18-09-2019 - |
题
我正在尝试编写一个脚本,该脚本将自动更新通过Google网站创建和管理的网站上的某些附件。当Google发布 站点API 在9月和 Python Gdata API 声称支持网站。但是,我可以找到的最接近的方法称为 client.update
, ,这使我可以更新附件的元数据,但不能更新内容。
在Java API中更新附件是通过创建新的 MediaFileSource
然后打电话 entry.setMediaFileSource(source)
其次是 entry.updateMedia()
. 。但是,我在Python API中找不到类似的东西。我是愚蠢的,只是缺少某些东西,还是真的不可能使用Python API更新Google站点附件?
解决方案
站点API已更新为v1.1;这可能是一个新的补充
http://code.google.com/apis/sites/docs/1.0/developers_guide_python.html#updatingcontent
其他提示
文档 这里 提供了一个有关如何更新附件的内容和元数据的示例(替换附件的内容和元数据)
唯一遗漏的是 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
好的,那里的API很奇怪,并且文档不太清楚。这是我想出的。首次上传附件时,您可以通过上传方法进行操作,但是在后续尝试中,您需要调用更新。这是执行此操作的代码:
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
有一个 upload_attachment 方法,应该有效。您可能还想检查一下 示例代码 对于站点API,它使用该方法。
不隶属于 StackOverflow