/gdata/__init__.py

http://radioappz.googlecode.com/ · Python · 835 lines · 662 code · 82 blank · 91 comment · 44 complexity · 5dcaa4ad36cb319798ea710077c41115 MD5 · raw file

  1. #!/usr/bin/python
  2. #
  3. # Copyright (C) 2006 Google Inc.
  4. #
  5. # Licensed under the Apache License, Version 2.0 (the "License");
  6. # you may not use this file except in compliance with the License.
  7. # You may obtain a copy of the License at
  8. #
  9. # http://www.apache.org/licenses/LICENSE-2.0
  10. #
  11. # Unless required by applicable law or agreed to in writing, software
  12. # distributed under the License is distributed on an "AS IS" BASIS,
  13. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  14. # See the License for the specific language governing permissions and
  15. # limitations under the License.
  16. """Contains classes representing Google Data elements.
  17. Extends Atom classes to add Google Data specific elements.
  18. """
  19. __author__ = 'j.s@google.com (Jeffrey Scudder)'
  20. import os
  21. import atom
  22. try:
  23. from xml.etree import cElementTree as ElementTree
  24. except ImportError:
  25. try:
  26. import cElementTree as ElementTree
  27. except ImportError:
  28. try:
  29. from xml.etree import ElementTree
  30. except ImportError:
  31. from elementtree import ElementTree
  32. # XML namespaces which are often used in GData entities.
  33. GDATA_NAMESPACE = 'http://schemas.google.com/g/2005'
  34. GDATA_TEMPLATE = '{http://schemas.google.com/g/2005}%s'
  35. OPENSEARCH_NAMESPACE = 'http://a9.com/-/spec/opensearchrss/1.0/'
  36. OPENSEARCH_TEMPLATE = '{http://a9.com/-/spec/opensearchrss/1.0/}%s'
  37. BATCH_NAMESPACE = 'http://schemas.google.com/gdata/batch'
  38. GACL_NAMESPACE = 'http://schemas.google.com/acl/2007'
  39. GACL_TEMPLATE = '{http://schemas.google.com/acl/2007}%s'
  40. # Labels used in batch request entries to specify the desired CRUD operation.
  41. BATCH_INSERT = 'insert'
  42. BATCH_UPDATE = 'update'
  43. BATCH_DELETE = 'delete'
  44. BATCH_QUERY = 'query'
  45. class Error(Exception):
  46. pass
  47. class MissingRequiredParameters(Error):
  48. pass
  49. class MediaSource(object):
  50. """GData Entries can refer to media sources, so this class provides a
  51. place to store references to these objects along with some metadata.
  52. """
  53. def __init__(self, file_handle=None, content_type=None, content_length=None,
  54. file_path=None, file_name=None):
  55. """Creates an object of type MediaSource.
  56. Args:
  57. file_handle: A file handle pointing to the file to be encapsulated in the
  58. MediaSource
  59. content_type: string The MIME type of the file. Required if a file_handle
  60. is given.
  61. content_length: int The size of the file. Required if a file_handle is
  62. given.
  63. file_path: string (optional) A full path name to the file. Used in
  64. place of a file_handle.
  65. file_name: string The name of the file without any path information.
  66. Required if a file_handle is given.
  67. """
  68. self.file_handle = file_handle
  69. self.content_type = content_type
  70. self.content_length = content_length
  71. self.file_name = file_name
  72. if (file_handle is None and content_type is not None and
  73. file_path is not None):
  74. self.setFile(file_path, content_type)
  75. def setFile(self, file_name, content_type):
  76. """A helper function which can create a file handle from a given filename
  77. and set the content type and length all at once.
  78. Args:
  79. file_name: string The path and file name to the file containing the media
  80. content_type: string A MIME type representing the type of the media
  81. """
  82. self.file_handle = open(file_name, 'rb')
  83. self.content_type = content_type
  84. self.content_length = os.path.getsize(file_name)
  85. self.file_name = os.path.basename(file_name)
  86. class LinkFinder(atom.LinkFinder):
  87. """An "interface" providing methods to find link elements
  88. GData Entry elements often contain multiple links which differ in the rel
  89. attribute or content type. Often, developers are interested in a specific
  90. type of link so this class provides methods to find specific classes of
  91. links.
  92. This class is used as a mixin in GData entries.
  93. """
  94. def GetSelfLink(self):
  95. """Find the first link with rel set to 'self'
  96. Returns:
  97. An atom.Link or none if none of the links had rel equal to 'self'
  98. """
  99. for a_link in self.link:
  100. if a_link.rel == 'self':
  101. return a_link
  102. return None
  103. def GetEditLink(self):
  104. for a_link in self.link:
  105. if a_link.rel == 'edit':
  106. return a_link
  107. return None
  108. def GetEditMediaLink(self):
  109. """The Picasa API mistakenly returns media-edit rather than edit-media, but
  110. this may change soon.
  111. """
  112. for a_link in self.link:
  113. if a_link.rel == 'edit-media':
  114. return a_link
  115. if a_link.rel == 'media-edit':
  116. return a_link
  117. return None
  118. def GetHtmlLink(self):
  119. """Find the first link with rel of alternate and type of text/html
  120. Returns:
  121. An atom.Link or None if no links matched
  122. """
  123. for a_link in self.link:
  124. if a_link.rel == 'alternate' and a_link.type == 'text/html':
  125. return a_link
  126. return None
  127. def GetPostLink(self):
  128. """Get a link containing the POST target URL.
  129. The POST target URL is used to insert new entries.
  130. Returns:
  131. A link object with a rel matching the POST type.
  132. """
  133. for a_link in self.link:
  134. if a_link.rel == 'http://schemas.google.com/g/2005#post':
  135. return a_link
  136. return None
  137. def GetAclLink(self):
  138. for a_link in self.link:
  139. if a_link.rel == 'http://schemas.google.com/acl/2007#accessControlList':
  140. return a_link
  141. return None
  142. def GetFeedLink(self):
  143. for a_link in self.link:
  144. if a_link.rel == 'http://schemas.google.com/g/2005#feed':
  145. return a_link
  146. return None
  147. def GetNextLink(self):
  148. for a_link in self.link:
  149. if a_link.rel == 'next':
  150. return a_link
  151. return None
  152. def GetPrevLink(self):
  153. for a_link in self.link:
  154. if a_link.rel == 'previous':
  155. return a_link
  156. return None
  157. class TotalResults(atom.AtomBase):
  158. """opensearch:TotalResults for a GData feed"""
  159. _tag = 'totalResults'
  160. _namespace = OPENSEARCH_NAMESPACE
  161. _children = atom.AtomBase._children.copy()
  162. _attributes = atom.AtomBase._attributes.copy()
  163. def __init__(self, extension_elements=None,
  164. extension_attributes=None, text=None):
  165. self.text = text
  166. self.extension_elements = extension_elements or []
  167. self.extension_attributes = extension_attributes or {}
  168. def TotalResultsFromString(xml_string):
  169. return atom.CreateClassFromXMLString(TotalResults, xml_string)
  170. class StartIndex(atom.AtomBase):
  171. """The opensearch:startIndex element in GData feed"""
  172. _tag = 'startIndex'
  173. _namespace = OPENSEARCH_NAMESPACE
  174. _children = atom.AtomBase._children.copy()
  175. _attributes = atom.AtomBase._attributes.copy()
  176. def __init__(self, extension_elements=None,
  177. extension_attributes=None, text=None):
  178. self.text = text
  179. self.extension_elements = extension_elements or []
  180. self.extension_attributes = extension_attributes or {}
  181. def StartIndexFromString(xml_string):
  182. return atom.CreateClassFromXMLString(StartIndex, xml_string)
  183. class ItemsPerPage(atom.AtomBase):
  184. """The opensearch:itemsPerPage element in GData feed"""
  185. _tag = 'itemsPerPage'
  186. _namespace = OPENSEARCH_NAMESPACE
  187. _children = atom.AtomBase._children.copy()
  188. _attributes = atom.AtomBase._attributes.copy()
  189. def __init__(self, extension_elements=None,
  190. extension_attributes=None, text=None):
  191. self.text = text
  192. self.extension_elements = extension_elements or []
  193. self.extension_attributes = extension_attributes or {}
  194. def ItemsPerPageFromString(xml_string):
  195. return atom.CreateClassFromXMLString(ItemsPerPage, xml_string)
  196. class ExtendedProperty(atom.AtomBase):
  197. """The Google Data extendedProperty element.
  198. Used to store arbitrary key-value information specific to your
  199. application. The value can either be a text string stored as an XML
  200. attribute (.value), or an XML node (XmlBlob) as a child element.
  201. This element is used in the Google Calendar data API and the Google
  202. Contacts data API.
  203. """
  204. _tag = 'extendedProperty'
  205. _namespace = GDATA_NAMESPACE
  206. _children = atom.AtomBase._children.copy()
  207. _attributes = atom.AtomBase._attributes.copy()
  208. _attributes['name'] = 'name'
  209. _attributes['value'] = 'value'
  210. def __init__(self, name=None, value=None, extension_elements=None,
  211. extension_attributes=None, text=None):
  212. self.name = name
  213. self.value = value
  214. self.text = text
  215. self.extension_elements = extension_elements or []
  216. self.extension_attributes = extension_attributes or {}
  217. def GetXmlBlobExtensionElement(self):
  218. """Returns the XML blob as an atom.ExtensionElement.
  219. Returns:
  220. An atom.ExtensionElement representing the blob's XML, or None if no
  221. blob was set.
  222. """
  223. if len(self.extension_elements) < 1:
  224. return None
  225. else:
  226. return self.extension_elements[0]
  227. def GetXmlBlobString(self):
  228. """Returns the XML blob as a string.
  229. Returns:
  230. A string containing the blob's XML, or None if no blob was set.
  231. """
  232. blob = self.GetXmlBlobExtensionElement()
  233. if blob:
  234. return blob.ToString()
  235. return None
  236. def SetXmlBlob(self, blob):
  237. """Sets the contents of the extendedProperty to XML as a child node.
  238. Since the extendedProperty is only allowed one child element as an XML
  239. blob, setting the XML blob will erase any preexisting extension elements
  240. in this object.
  241. Args:
  242. blob: str, ElementTree Element or atom.ExtensionElement representing
  243. the XML blob stored in the extendedProperty.
  244. """
  245. # Erase any existing extension_elements, clears the child nodes from the
  246. # extendedProperty.
  247. self.extension_elements = []
  248. if isinstance(blob, atom.ExtensionElement):
  249. self.extension_elements.append(blob)
  250. elif ElementTree.iselement(blob):
  251. self.extension_elements.append(atom._ExtensionElementFromElementTree(
  252. blob))
  253. else:
  254. self.extension_elements.append(atom.ExtensionElementFromString(blob))
  255. def ExtendedPropertyFromString(xml_string):
  256. return atom.CreateClassFromXMLString(ExtendedProperty, xml_string)
  257. class GDataEntry(atom.Entry, LinkFinder):
  258. """Extends Atom Entry to provide data processing"""
  259. _tag = atom.Entry._tag
  260. _namespace = atom.Entry._namespace
  261. _children = atom.Entry._children.copy()
  262. _attributes = atom.Entry._attributes.copy()
  263. def __GetId(self):
  264. return self.__id
  265. # This method was created to strip the unwanted whitespace from the id's
  266. # text node.
  267. def __SetId(self, id):
  268. self.__id = id
  269. if id is not None and id.text is not None:
  270. self.__id.text = id.text.strip()
  271. id = property(__GetId, __SetId)
  272. def IsMedia(self):
  273. """Determines whether or not an entry is a GData Media entry.
  274. """
  275. if (self.GetEditMediaLink()):
  276. return True
  277. else:
  278. return False
  279. def GetMediaURL(self):
  280. """Returns the URL to the media content, if the entry is a media entry.
  281. Otherwise returns None.
  282. """
  283. if not self.IsMedia():
  284. return None
  285. else:
  286. return self.content.src
  287. def GDataEntryFromString(xml_string):
  288. """Creates a new GDataEntry instance given a string of XML."""
  289. return atom.CreateClassFromXMLString(GDataEntry, xml_string)
  290. class GDataFeed(atom.Feed, LinkFinder):
  291. """A Feed from a GData service"""
  292. _tag = 'feed'
  293. _namespace = atom.ATOM_NAMESPACE
  294. _children = atom.Feed._children.copy()
  295. _attributes = atom.Feed._attributes.copy()
  296. _children['{%s}totalResults' % OPENSEARCH_NAMESPACE] = ('total_results',
  297. TotalResults)
  298. _children['{%s}startIndex' % OPENSEARCH_NAMESPACE] = ('start_index',
  299. StartIndex)
  300. _children['{%s}itemsPerPage' % OPENSEARCH_NAMESPACE] = ('items_per_page',
  301. ItemsPerPage)
  302. # Add a conversion rule for atom:entry to make it into a GData
  303. # Entry.
  304. _children['{%s}entry' % atom.ATOM_NAMESPACE] = ('entry', [GDataEntry])
  305. def __GetId(self):
  306. return self.__id
  307. def __SetId(self, id):
  308. self.__id = id
  309. if id is not None and id.text is not None:
  310. self.__id.text = id.text.strip()
  311. id = property(__GetId, __SetId)
  312. def __GetGenerator(self):
  313. return self.__generator
  314. def __SetGenerator(self, generator):
  315. self.__generator = generator
  316. if generator is not None:
  317. self.__generator.text = generator.text.strip()
  318. generator = property(__GetGenerator, __SetGenerator)
  319. def __init__(self, author=None, category=None, contributor=None,
  320. generator=None, icon=None, atom_id=None, link=None, logo=None,
  321. rights=None, subtitle=None, title=None, updated=None, entry=None,
  322. total_results=None, start_index=None, items_per_page=None,
  323. extension_elements=None, extension_attributes=None, text=None):
  324. """Constructor for Source
  325. Args:
  326. author: list (optional) A list of Author instances which belong to this
  327. class.
  328. category: list (optional) A list of Category instances
  329. contributor: list (optional) A list on Contributor instances
  330. generator: Generator (optional)
  331. icon: Icon (optional)
  332. id: Id (optional) The entry's Id element
  333. link: list (optional) A list of Link instances
  334. logo: Logo (optional)
  335. rights: Rights (optional) The entry's Rights element
  336. subtitle: Subtitle (optional) The entry's subtitle element
  337. title: Title (optional) the entry's title element
  338. updated: Updated (optional) the entry's updated element
  339. entry: list (optional) A list of the Entry instances contained in the
  340. feed.
  341. text: String (optional) The text contents of the element. This is the
  342. contents of the Entry's XML text node.
  343. (Example: <foo>This is the text</foo>)
  344. extension_elements: list (optional) A list of ExtensionElement instances
  345. which are children of this element.
  346. extension_attributes: dict (optional) A dictionary of strings which are
  347. the values for additional XML attributes of this element.
  348. """
  349. self.author = author or []
  350. self.category = category or []
  351. self.contributor = contributor or []
  352. self.generator = generator
  353. self.icon = icon
  354. self.id = atom_id
  355. self.link = link or []
  356. self.logo = logo
  357. self.rights = rights
  358. self.subtitle = subtitle
  359. self.title = title
  360. self.updated = updated
  361. self.entry = entry or []
  362. self.total_results = total_results
  363. self.start_index = start_index
  364. self.items_per_page = items_per_page
  365. self.text = text
  366. self.extension_elements = extension_elements or []
  367. self.extension_attributes = extension_attributes or {}
  368. def GDataFeedFromString(xml_string):
  369. return atom.CreateClassFromXMLString(GDataFeed, xml_string)
  370. class BatchId(atom.AtomBase):
  371. _tag = 'id'
  372. _namespace = BATCH_NAMESPACE
  373. _children = atom.AtomBase._children.copy()
  374. _attributes = atom.AtomBase._attributes.copy()
  375. def BatchIdFromString(xml_string):
  376. return atom.CreateClassFromXMLString(BatchId, xml_string)
  377. class BatchOperation(atom.AtomBase):
  378. _tag = 'operation'
  379. _namespace = BATCH_NAMESPACE
  380. _children = atom.AtomBase._children.copy()
  381. _attributes = atom.AtomBase._attributes.copy()
  382. _attributes['type'] = 'type'
  383. def __init__(self, op_type=None, extension_elements=None,
  384. extension_attributes=None,
  385. text=None):
  386. self.type = op_type
  387. atom.AtomBase.__init__(self,
  388. extension_elements=extension_elements,
  389. extension_attributes=extension_attributes,
  390. text=text)
  391. def BatchOperationFromString(xml_string):
  392. return atom.CreateClassFromXMLString(BatchOperation, xml_string)
  393. class BatchStatus(atom.AtomBase):
  394. """The batch:status element present in a batch response entry.
  395. A status element contains the code (HTTP response code) and
  396. reason as elements. In a single request these fields would
  397. be part of the HTTP response, but in a batch request each
  398. Entry operation has a corresponding Entry in the response
  399. feed which includes status information.
  400. See http://code.google.com/apis/gdata/batch.html#Handling_Errors
  401. """
  402. _tag = 'status'
  403. _namespace = BATCH_NAMESPACE
  404. _children = atom.AtomBase._children.copy()
  405. _attributes = atom.AtomBase._attributes.copy()
  406. _attributes['code'] = 'code'
  407. _attributes['reason'] = 'reason'
  408. _attributes['content-type'] = 'content_type'
  409. def __init__(self, code=None, reason=None, content_type=None,
  410. extension_elements=None, extension_attributes=None, text=None):
  411. self.code = code
  412. self.reason = reason
  413. self.content_type = content_type
  414. atom.AtomBase.__init__(self, extension_elements=extension_elements,
  415. extension_attributes=extension_attributes,
  416. text=text)
  417. def BatchStatusFromString(xml_string):
  418. return atom.CreateClassFromXMLString(BatchStatus, xml_string)
  419. class BatchEntry(GDataEntry):
  420. """An atom:entry for use in batch requests.
  421. The BatchEntry contains additional members to specify the operation to be
  422. performed on this entry and a batch ID so that the server can reference
  423. individual operations in the response feed. For more information, see:
  424. http://code.google.com/apis/gdata/batch.html
  425. """
  426. _tag = GDataEntry._tag
  427. _namespace = GDataEntry._namespace
  428. _children = GDataEntry._children.copy()
  429. _children['{%s}operation' % BATCH_NAMESPACE] = ('batch_operation', BatchOperation)
  430. _children['{%s}id' % BATCH_NAMESPACE] = ('batch_id', BatchId)
  431. _children['{%s}status' % BATCH_NAMESPACE] = ('batch_status', BatchStatus)
  432. _attributes = GDataEntry._attributes.copy()
  433. def __init__(self, author=None, category=None, content=None,
  434. contributor=None, atom_id=None, link=None, published=None, rights=None,
  435. source=None, summary=None, control=None, title=None, updated=None,
  436. batch_operation=None, batch_id=None, batch_status=None,
  437. extension_elements=None, extension_attributes=None, text=None):
  438. self.batch_operation = batch_operation
  439. self.batch_id = batch_id
  440. self.batch_status = batch_status
  441. GDataEntry.__init__(self, author=author, category=category,
  442. content=content, contributor=contributor, atom_id=atom_id, link=link,
  443. published=published, rights=rights, source=source, summary=summary,
  444. control=control, title=title, updated=updated,
  445. extension_elements=extension_elements,
  446. extension_attributes=extension_attributes, text=text)
  447. def BatchEntryFromString(xml_string):
  448. return atom.CreateClassFromXMLString(BatchEntry, xml_string)
  449. class BatchInterrupted(atom.AtomBase):
  450. """The batch:interrupted element sent if batch request was interrupted.
  451. Only appears in a feed if some of the batch entries could not be processed.
  452. See: http://code.google.com/apis/gdata/batch.html#Handling_Errors
  453. """
  454. _tag = 'interrupted'
  455. _namespace = BATCH_NAMESPACE
  456. _children = atom.AtomBase._children.copy()
  457. _attributes = atom.AtomBase._attributes.copy()
  458. _attributes['reason'] = 'reason'
  459. _attributes['success'] = 'success'
  460. _attributes['failures'] = 'failures'
  461. _attributes['parsed'] = 'parsed'
  462. def __init__(self, reason=None, success=None, failures=None, parsed=None,
  463. extension_elements=None, extension_attributes=None, text=None):
  464. self.reason = reason
  465. self.success = success
  466. self.failures = failures
  467. self.parsed = parsed
  468. atom.AtomBase.__init__(self, extension_elements=extension_elements,
  469. extension_attributes=extension_attributes,
  470. text=text)
  471. def BatchInterruptedFromString(xml_string):
  472. return atom.CreateClassFromXMLString(BatchInterrupted, xml_string)
  473. class BatchFeed(GDataFeed):
  474. """A feed containing a list of batch request entries."""
  475. _tag = GDataFeed._tag
  476. _namespace = GDataFeed._namespace
  477. _children = GDataFeed._children.copy()
  478. _attributes = GDataFeed._attributes.copy()
  479. _children['{%s}entry' % atom.ATOM_NAMESPACE] = ('entry', [BatchEntry])
  480. _children['{%s}interrupted' % BATCH_NAMESPACE] = ('interrupted', BatchInterrupted)
  481. def __init__(self, author=None, category=None, contributor=None,
  482. generator=None, icon=None, atom_id=None, link=None, logo=None,
  483. rights=None, subtitle=None, title=None, updated=None, entry=None,
  484. total_results=None, start_index=None, items_per_page=None,
  485. interrupted=None,
  486. extension_elements=None, extension_attributes=None, text=None):
  487. self.interrupted = interrupted
  488. GDataFeed.__init__(self, author=author, category=category,
  489. contributor=contributor, generator=generator,
  490. icon=icon, atom_id=atom_id, link=link,
  491. logo=logo, rights=rights, subtitle=subtitle,
  492. title=title, updated=updated, entry=entry,
  493. total_results=total_results, start_index=start_index,
  494. items_per_page=items_per_page,
  495. extension_elements=extension_elements,
  496. extension_attributes=extension_attributes,
  497. text=text)
  498. def AddBatchEntry(self, entry=None, id_url_string=None,
  499. batch_id_string=None, operation_string=None):
  500. """Logic for populating members of a BatchEntry and adding to the feed.
  501. If the entry is not a BatchEntry, it is converted to a BatchEntry so
  502. that the batch specific members will be present.
  503. The id_url_string can be used in place of an entry if the batch operation
  504. applies to a URL. For example query and delete operations require just
  505. the URL of an entry, no body is sent in the HTTP request. If an
  506. id_url_string is sent instead of an entry, a BatchEntry is created and
  507. added to the feed.
  508. This method also assigns the desired batch id to the entry so that it
  509. can be referenced in the server's response. If the batch_id_string is
  510. None, this method will assign a batch_id to be the index at which this
  511. entry will be in the feed's entry list.
  512. Args:
  513. entry: BatchEntry, atom.Entry, or another Entry flavor (optional) The
  514. entry which will be sent to the server as part of the batch request.
  515. The item must have a valid atom id so that the server knows which
  516. entry this request references.
  517. id_url_string: str (optional) The URL of the entry to be acted on. You
  518. can find this URL in the text member of the atom id for an entry.
  519. If an entry is not sent, this id will be used to construct a new
  520. BatchEntry which will be added to the request feed.
  521. batch_id_string: str (optional) The batch ID to be used to reference
  522. this batch operation in the results feed. If this parameter is None,
  523. the current length of the feed's entry array will be used as a
  524. count. Note that batch_ids should either always be specified or
  525. never, mixing could potentially result in duplicate batch ids.
  526. operation_string: str (optional) The desired batch operation which will
  527. set the batch_operation.type member of the entry. Options are
  528. 'insert', 'update', 'delete', and 'query'
  529. Raises:
  530. MissingRequiredParameters: Raised if neither an id_ url_string nor an
  531. entry are provided in the request.
  532. Returns:
  533. The added entry.
  534. """
  535. if entry is None and id_url_string is None:
  536. raise MissingRequiredParameters('supply either an entry or URL string')
  537. if entry is None and id_url_string is not None:
  538. entry = BatchEntry(atom_id=atom.Id(text=id_url_string))
  539. # TODO: handle cases in which the entry lacks batch_... members.
  540. #if not isinstance(entry, BatchEntry):
  541. # Convert the entry to a batch entry.
  542. if batch_id_string is not None:
  543. entry.batch_id = BatchId(text=batch_id_string)
  544. elif entry.batch_id is None or entry.batch_id.text is None:
  545. entry.batch_id = BatchId(text=str(len(self.entry)))
  546. if operation_string is not None:
  547. entry.batch_operation = BatchOperation(op_type=operation_string)
  548. self.entry.append(entry)
  549. return entry
  550. def AddInsert(self, entry, batch_id_string=None):
  551. """Add an insert request to the operations in this batch request feed.
  552. If the entry doesn't yet have an operation or a batch id, these will
  553. be set to the insert operation and a batch_id specified as a parameter.
  554. Args:
  555. entry: BatchEntry The entry which will be sent in the batch feed as an
  556. insert request.
  557. batch_id_string: str (optional) The batch ID to be used to reference
  558. this batch operation in the results feed. If this parameter is None,
  559. the current length of the feed's entry array will be used as a
  560. count. Note that batch_ids should either always be specified or
  561. never, mixing could potentially result in duplicate batch ids.
  562. """
  563. entry = self.AddBatchEntry(entry=entry, batch_id_string=batch_id_string,
  564. operation_string=BATCH_INSERT)
  565. def AddUpdate(self, entry, batch_id_string=None):
  566. """Add an update request to the list of batch operations in this feed.
  567. Sets the operation type of the entry to insert if it is not already set
  568. and assigns the desired batch id to the entry so that it can be
  569. referenced in the server's response.
  570. Args:
  571. entry: BatchEntry The entry which will be sent to the server as an
  572. update (HTTP PUT) request. The item must have a valid atom id
  573. so that the server knows which entry to replace.
  574. batch_id_string: str (optional) The batch ID to be used to reference
  575. this batch operation in the results feed. If this parameter is None,
  576. the current length of the feed's entry array will be used as a
  577. count. See also comments for AddInsert.
  578. """
  579. entry = self.AddBatchEntry(entry=entry, batch_id_string=batch_id_string,
  580. operation_string=BATCH_UPDATE)
  581. def AddDelete(self, url_string=None, entry=None, batch_id_string=None):
  582. """Adds a delete request to the batch request feed.
  583. This method takes either the url_string which is the atom id of the item
  584. to be deleted, or the entry itself. The atom id of the entry must be
  585. present so that the server knows which entry should be deleted.
  586. Args:
  587. url_string: str (optional) The URL of the entry to be deleted. You can
  588. find this URL in the text member of the atom id for an entry.
  589. entry: BatchEntry (optional) The entry to be deleted.
  590. batch_id_string: str (optional)
  591. Raises:
  592. MissingRequiredParameters: Raised if neither a url_string nor an entry
  593. are provided in the request.
  594. """
  595. entry = self.AddBatchEntry(entry=entry, id_url_string=url_string,
  596. batch_id_string=batch_id_string,
  597. operation_string=BATCH_DELETE)
  598. def AddQuery(self, url_string=None, entry=None, batch_id_string=None):
  599. """Adds a query request to the batch request feed.
  600. This method takes either the url_string which is the query URL
  601. whose results will be added to the result feed. The query URL will
  602. be encapsulated in a BatchEntry, and you may pass in the BatchEntry
  603. with a query URL instead of sending a url_string.
  604. Args:
  605. url_string: str (optional)
  606. entry: BatchEntry (optional)
  607. batch_id_string: str (optional)
  608. Raises:
  609. MissingRequiredParameters
  610. """
  611. entry = self.AddBatchEntry(entry=entry, id_url_string=url_string,
  612. batch_id_string=batch_id_string,
  613. operation_string=BATCH_QUERY)
  614. def GetBatchLink(self):
  615. for link in self.link:
  616. if link.rel == 'http://schemas.google.com/g/2005#batch':
  617. return link
  618. return None
  619. def BatchFeedFromString(xml_string):
  620. return atom.CreateClassFromXMLString(BatchFeed, xml_string)
  621. class EntryLink(atom.AtomBase):
  622. """The gd:entryLink element"""
  623. _tag = 'entryLink'
  624. _namespace = GDATA_NAMESPACE
  625. _children = atom.AtomBase._children.copy()
  626. _attributes = atom.AtomBase._attributes.copy()
  627. # The entry used to be an atom.Entry, now it is a GDataEntry.
  628. _children['{%s}entry' % atom.ATOM_NAMESPACE] = ('entry', GDataEntry)
  629. _attributes['rel'] = 'rel'
  630. _attributes['readOnly'] = 'read_only'
  631. _attributes['href'] = 'href'
  632. def __init__(self, href=None, read_only=None, rel=None,
  633. entry=None, extension_elements=None,
  634. extension_attributes=None, text=None):
  635. self.href = href
  636. self.read_only = read_only
  637. self.rel = rel
  638. self.entry = entry
  639. self.text = text
  640. self.extension_elements = extension_elements or []
  641. self.extension_attributes = extension_attributes or {}
  642. def EntryLinkFromString(xml_string):
  643. return atom.CreateClassFromXMLString(EntryLink, xml_string)
  644. class FeedLink(atom.AtomBase):
  645. """The gd:feedLink element"""
  646. _tag = 'feedLink'
  647. _namespace = GDATA_NAMESPACE
  648. _children = atom.AtomBase._children.copy()
  649. _attributes = atom.AtomBase._attributes.copy()
  650. _children['{%s}feed' % atom.ATOM_NAMESPACE] = ('feed', GDataFeed)
  651. _attributes['rel'] = 'rel'
  652. _attributes['readOnly'] = 'read_only'
  653. _attributes['countHint'] = 'count_hint'
  654. _attributes['href'] = 'href'
  655. def __init__(self, count_hint=None, href=None, read_only=None, rel=None,
  656. feed=None, extension_elements=None, extension_attributes=None,
  657. text=None):
  658. self.count_hint = count_hint
  659. self.href = href
  660. self.read_only = read_only
  661. self.rel = rel
  662. self.feed = feed
  663. self.text = text
  664. self.extension_elements = extension_elements or []
  665. self.extension_attributes = extension_attributes or {}
  666. def FeedLinkFromString(xml_string):
  667. return atom.CreateClassFromXMLString(FeedLink, xml_string)