/gdata/spreadsheets/client.py

http://radioappz.googlecode.com/ · Python · 451 lines · 199 code · 31 blank · 221 comment · 3 complexity · 987009f85fab2b3fc52867601296bada MD5 · raw file

  1. #!/usr/bin/env python
  2. #
  3. # Copyright (C) 2009 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 a client to communicate with the Google Spreadsheets servers.
  17. For documentation on the Spreadsheets API, see:
  18. http://code.google.com/apis/spreadsheets/
  19. """
  20. __author__ = 'j.s@google.com (Jeff Scudder)'
  21. import gdata.client
  22. import gdata.gauth
  23. import gdata.spreadsheets.data
  24. import atom.data
  25. import atom.http_core
  26. SPREADSHEETS_URL = ('http://spreadsheets.google.com/feeds/spreadsheets'
  27. '/private/full')
  28. WORKSHEETS_URL = ('http://spreadsheets.google.com/feeds/worksheets/'
  29. '%s/private/full')
  30. WORKSHEET_URL = ('http://spreadsheets.google.com/feeds/worksheets/'
  31. '%s/private/full/%s')
  32. TABLES_URL = 'http://spreadsheets.google.com/feeds/%s/tables'
  33. RECORDS_URL = 'http://spreadsheets.google.com/feeds/%s/records/%s'
  34. RECORD_URL = 'http://spreadsheets.google.com/feeds/%s/records/%s/%s'
  35. class SpreadsheetsClient(gdata.client.GDClient):
  36. api_version = '3'
  37. auth_service = 'wise'
  38. auth_scopes = gdata.gauth.AUTH_SCOPES['wise']
  39. def get_spreadsheets(self, auth_token=None,
  40. desired_class=gdata.spreadsheets.data.SpreadsheetsFeed,
  41. **kwargs):
  42. """Obtains a feed with the spreadsheets belonging to the current user.
  43. Args:
  44. auth_token: An object which sets the Authorization HTTP header in its
  45. modify_request method. Recommended classes include
  46. gdata.gauth.ClientLoginToken and gdata.gauth.AuthSubToken
  47. among others. Represents the current user. Defaults to None
  48. and if None, this method will look for a value in the
  49. auth_token member of SpreadsheetsClient.
  50. desired_class: class descended from atom.core.XmlElement to which a
  51. successful response should be converted. If there is no
  52. converter function specified (converter=None) then the
  53. desired_class will be used in calling the
  54. atom.core.parse function. If neither
  55. the desired_class nor the converter is specified, an
  56. HTTP reponse object will be returned. Defaults to
  57. gdata.spreadsheets.data.SpreadsheetsFeed.
  58. """
  59. return self.get_feed(SPREADSHEETS_URL, auth_token=auth_token,
  60. desired_class=desired_class, **kwargs)
  61. GetSpreadsheets = get_spreadsheets
  62. def get_worksheets(self, spreadsheet_key, auth_token=None,
  63. desired_class=gdata.spreadsheets.data.WorksheetsFeed,
  64. **kwargs):
  65. """Finds the worksheets within a given spreadsheet.
  66. Args:
  67. spreadsheet_key: str, The unique ID of this containing spreadsheet. This
  68. can be the ID from the URL or as provided in a
  69. Spreadsheet entry.
  70. auth_token: An object which sets the Authorization HTTP header in its
  71. modify_request method. Recommended classes include
  72. gdata.gauth.ClientLoginToken and gdata.gauth.AuthSubToken
  73. among others. Represents the current user. Defaults to None
  74. and if None, this method will look for a value in the
  75. auth_token member of SpreadsheetsClient.
  76. desired_class: class descended from atom.core.XmlElement to which a
  77. successful response should be converted. If there is no
  78. converter function specified (converter=None) then the
  79. desired_class will be used in calling the
  80. atom.core.parse function. If neither
  81. the desired_class nor the converter is specified, an
  82. HTTP reponse object will be returned. Defaults to
  83. gdata.spreadsheets.data.WorksheetsFeed.
  84. """
  85. return self.get_feed(WORKSHEETS_URL % spreadsheet_key,
  86. auth_token=auth_token, desired_class=desired_class,
  87. **kwargs)
  88. GetWorksheets = get_worksheets
  89. def add_worksheet(self, spreadsheet_key, title, rows, cols,
  90. auth_token=None, **kwargs):
  91. """Creates a new worksheet entry in the spreadsheet.
  92. Args:
  93. spreadsheet_key: str, The unique ID of this containing spreadsheet. This
  94. can be the ID from the URL or as provided in a
  95. Spreadsheet entry.
  96. title: str, The title to be used in for the worksheet.
  97. rows: str or int, The number of rows this worksheet should start with.
  98. cols: str or int, The number of columns this worksheet should start with.
  99. auth_token: An object which sets the Authorization HTTP header in its
  100. modify_request method. Recommended classes include
  101. gdata.gauth.ClientLoginToken and gdata.gauth.AuthSubToken
  102. among others. Represents the current user. Defaults to None
  103. and if None, this method will look for a value in the
  104. auth_token member of SpreadsheetsClient.
  105. """
  106. new_worksheet = gdata.spreadsheets.data.WorksheetEntry(
  107. title=atom.data.Title(text=title),
  108. row_count=gdata.spreadsheets.data.RowCount(text=str(rows)),
  109. col_count=gdata.spreadsheets.data.ColCount(text=str(cols)))
  110. return self.post(new_worksheet, WORKSHEETS_URL % spreadsheet_key,
  111. auth_token=auth_token, **kwargs)
  112. AddWorksheet = add_worksheet
  113. def get_worksheet(self, spreadsheet_key, worksheet_id,
  114. desired_class=gdata.spreadsheets.data.WorksheetEntry,
  115. auth_token=None, **kwargs):
  116. """Retrieves a single worksheet.
  117. Args:
  118. spreadsheet_key: str, The unique ID of this containing spreadsheet. This
  119. can be the ID from the URL or as provided in a
  120. Spreadsheet entry.
  121. worksheet_id: str, The unique ID for the worksheet withing the desired
  122. spreadsheet.
  123. auth_token: An object which sets the Authorization HTTP header in its
  124. modify_request method. Recommended classes include
  125. gdata.gauth.ClientLoginToken and gdata.gauth.AuthSubToken
  126. among others. Represents the current user. Defaults to None
  127. and if None, this method will look for a value in the
  128. auth_token member of SpreadsheetsClient.
  129. desired_class: class descended from atom.core.XmlElement to which a
  130. successful response should be converted. If there is no
  131. converter function specified (converter=None) then the
  132. desired_class will be used in calling the
  133. atom.core.parse function. If neither
  134. the desired_class nor the converter is specified, an
  135. HTTP reponse object will be returned. Defaults to
  136. gdata.spreadsheets.data.WorksheetEntry.
  137. """
  138. return self.get_entry(WORKSHEET_URL % (spreadsheet_key, worksheet_id,),
  139. auth_token=auth_token, desired_class=desired_class,
  140. **kwargs)
  141. GetWorksheet = get_worksheet
  142. def add_table(self, spreadsheet_key, title, summary, worksheet_name,
  143. header_row, num_rows, start_row, insertion_mode,
  144. column_headers, auth_token=None, **kwargs):
  145. """Creates a new table within the worksheet.
  146. Args:
  147. spreadsheet_key: str, The unique ID of this containing spreadsheet. This
  148. can be the ID from the URL or as provided in a
  149. Spreadsheet entry.
  150. title: str, The title for the new table within a worksheet.
  151. summary: str, A description of the table.
  152. worksheet_name: str The name of the worksheet in which this table
  153. should live.
  154. header_row: int or str, The number of the row in the worksheet which
  155. will contain the column names for the data in this table.
  156. num_rows: int or str, The number of adjacent rows in this table.
  157. start_row: int or str, The number of the row at which the data begins.
  158. insertion_mode: str
  159. column_headers: dict of strings, maps the column letters (A, B, C) to
  160. the desired name which will be viewable in the
  161. worksheet.
  162. auth_token: An object which sets the Authorization HTTP header in its
  163. modify_request method. Recommended classes include
  164. gdata.gauth.ClientLoginToken and gdata.gauth.AuthSubToken
  165. among others. Represents the current user. Defaults to None
  166. and if None, this method will look for a value in the
  167. auth_token member of SpreadsheetsClient.
  168. """
  169. data = gdata.spreadsheets.data.Data(
  170. insertion_mode=insertion_mode, num_rows=str(num_rows),
  171. start_row=str(start_row))
  172. for index, name in column_headers.iteritems():
  173. data.column.append(gdata.spreadsheets.data.Column(
  174. index=index, name=name))
  175. new_table = gdata.spreadsheets.data.Table(
  176. title=atom.data.Title(text=title), summary=atom.data.Summary(summary),
  177. worksheet=gdata.spreadsheets.data.Worksheet(name=worksheet_name),
  178. header=gdata.spreadsheets.data.Header(row=str(header_row)), data=data)
  179. return self.post(new_table, TABLES_URL % spreadsheet_key,
  180. auth_token=auth_token, **kwargs)
  181. AddTable = add_table
  182. def get_tables(self, spreadsheet_key,
  183. desired_class=gdata.spreadsheets.data.TablesFeed,
  184. auth_token=None, **kwargs):
  185. """Retrieves a feed listing the tables in this spreadsheet.
  186. Args:
  187. spreadsheet_key: str, The unique ID of this containing spreadsheet. This
  188. can be the ID from the URL or as provided in a
  189. Spreadsheet entry.
  190. desired_class: class descended from atom.core.XmlElement to which a
  191. successful response should be converted. If there is no
  192. converter function specified (converter=None) then the
  193. desired_class will be used in calling the
  194. atom.core.parse function. If neither
  195. the desired_class nor the converter is specified, an
  196. HTTP reponse object will be returned. Defaults to
  197. gdata.spreadsheets.data.TablesFeed.
  198. auth_token: An object which sets the Authorization HTTP header in its
  199. modify_request method. Recommended classes include
  200. gdata.gauth.ClientLoginToken and gdata.gauth.AuthSubToken
  201. among others. Represents the current user. Defaults to None
  202. and if None, this method will look for a value in the
  203. auth_token member of SpreadsheetsClient.
  204. """
  205. return self.get_feed(TABLES_URL % spreadsheet_key,
  206. desired_class=desired_class, auth_token=auth_token,
  207. **kwargs)
  208. GetTables = get_tables
  209. def add_record(self, spreadsheet_key, table_id, fields,
  210. title=None, auth_token=None, **kwargs):
  211. """Adds a new row to the table.
  212. Args:
  213. spreadsheet_key: str, The unique ID of this containing spreadsheet. This
  214. can be the ID from the URL or as provided in a
  215. Spreadsheet entry.
  216. table_id: str, The ID of the table within the worksheet which should
  217. receive this new record. The table ID can be found using the
  218. get_table_id method of a gdata.spreadsheets.data.Table.
  219. fields: dict of strings mapping column names to values.
  220. title: str, optional The title for this row.
  221. auth_token: An object which sets the Authorization HTTP header in its
  222. modify_request method. Recommended classes include
  223. gdata.gauth.ClientLoginToken and gdata.gauth.AuthSubToken
  224. among others. Represents the current user. Defaults to None
  225. and if None, this method will look for a value in the
  226. auth_token member of SpreadsheetsClient.
  227. """
  228. new_record = gdata.spreadsheets.data.Record()
  229. if title is not None:
  230. new_record.title = atom.data.Title(text=title)
  231. for name, value in fields.iteritems():
  232. new_record.field.append(gdata.spreadsheets.data.Field(
  233. name=name, text=value))
  234. return self.post(new_record, RECORDS_URL % (spreadsheet_key, table_id),
  235. auth_token=auth_token, **kwargs)
  236. AddRecord = add_record
  237. def get_records(self, spreadsheet_key, table_id,
  238. desired_class=gdata.spreadsheets.data.RecordsFeed,
  239. auth_token=None, **kwargs):
  240. """Retrieves the records in a table.
  241. Args:
  242. spreadsheet_key: str, The unique ID of this containing spreadsheet. This
  243. can be the ID from the URL or as provided in a
  244. Spreadsheet entry.
  245. table_id: str, The ID of the table within the worksheet whose records
  246. we would like to fetch. The table ID can be found using the
  247. get_table_id method of a gdata.spreadsheets.data.Table.
  248. desired_class: class descended from atom.core.XmlElement to which a
  249. successful response should be converted. If there is no
  250. converter function specified (converter=None) then the
  251. desired_class will be used in calling the
  252. atom.core.parse function. If neither
  253. the desired_class nor the converter is specified, an
  254. HTTP reponse object will be returned. Defaults to
  255. gdata.spreadsheets.data.RecordsFeed.
  256. auth_token: An object which sets the Authorization HTTP header in its
  257. modify_request method. Recommended classes include
  258. gdata.gauth.ClientLoginToken and gdata.gauth.AuthSubToken
  259. among others. Represents the current user. Defaults to None
  260. and if None, this method will look for a value in the
  261. auth_token member of SpreadsheetsClient.
  262. """
  263. return self.get_feed(RECORDS_URL % (spreadsheet_key, table_id),
  264. desired_class=desired_class, auth_token=auth_token,
  265. **kwargs)
  266. GetRecords = get_records
  267. def get_record(self, spreadsheet_key, table_id, record_id,
  268. desired_class=gdata.spreadsheets.data.Record,
  269. auth_token=None, **kwargs):
  270. """Retrieves a single record from the table.
  271. Args:
  272. spreadsheet_key: str, The unique ID of this containing spreadsheet. This
  273. can be the ID from the URL or as provided in a
  274. Spreadsheet entry.
  275. table_id: str, The ID of the table within the worksheet whose records
  276. we would like to fetch. The table ID can be found using the
  277. get_table_id method of a gdata.spreadsheets.data.Table.
  278. record_id: str, The ID of the record within this table which we want to
  279. fetch. You can find the record ID using get_record_id() on
  280. an instance of the gdata.spreadsheets.data.Record class.
  281. desired_class: class descended from atom.core.XmlElement to which a
  282. successful response should be converted. If there is no
  283. converter function specified (converter=None) then the
  284. desired_class will be used in calling the
  285. atom.core.parse function. If neither
  286. the desired_class nor the converter is specified, an
  287. HTTP reponse object will be returned. Defaults to
  288. gdata.spreadsheets.data.RecordsFeed.
  289. auth_token: An object which sets the Authorization HTTP header in its
  290. modify_request method. Recommended classes include
  291. gdata.gauth.ClientLoginToken and gdata.gauth.AuthSubToken
  292. among others. Represents the current user. Defaults to None
  293. and if None, this method will look for a value in the
  294. auth_token member of SpreadsheetsClient."""
  295. return self.get_entry(RECORD_URL % (spreadsheet_key, table_id, record_id),
  296. desired_class=desired_class, auth_token=auth_token,
  297. **kwargs)
  298. GetRecord = get_record
  299. class SpreadsheetQuery(gdata.client.Query):
  300. def __init__(self, title=None, title_exact=None, **kwargs):
  301. """Adds Spreadsheets feed query parameters to a request.
  302. Args:
  303. title: str Specifies the search terms for the title of a document.
  304. This parameter used without title-exact will only submit partial
  305. queries, not exact queries.
  306. title_exact: str Specifies whether the title query should be taken as an
  307. exact string. Meaningless without title. Possible values are
  308. 'true' and 'false'.
  309. """
  310. gdata.client.Query.__init__(self, **kwargs)
  311. self.title = title
  312. self.title_exact = title_exact
  313. def modify_request(self, http_request):
  314. gdata.client._add_query_param('title', self.title, http_request)
  315. gdata.client._add_query_param('title-exact', self.title_exact,
  316. http_request)
  317. gdata.client.Query.modify_request(self, http_request)
  318. ModifyRequest = modify_request
  319. class WorksheetQuery(SpreadsheetQuery):
  320. pass
  321. class ListQuery(gdata.client.Query):
  322. def __init__(self, order_by=None, reverse=None, sq=None, **kwargs):
  323. """Adds List-feed specific query parameters to a request.
  324. Args:
  325. order_by: str Specifies what column to use in ordering the entries in
  326. the feed. By position (the default): 'position' returns
  327. rows in the order in which they appear in the GUI. Row 1, then
  328. row 2, then row 3, and so on. By column:
  329. 'column:columnName' sorts rows in ascending order based on the
  330. values in the column with the given columnName, where
  331. columnName is the value in the header row for that column.
  332. reverse: str Specifies whether to sort in descending or ascending order.
  333. Reverses default sort order: 'true' results in a descending
  334. sort; 'false' (the default) results in an ascending sort.
  335. sq: str Structured query on the full text in the worksheet.
  336. [columnName][binaryOperator][value]
  337. Supported binaryOperators are:
  338. - (), for overriding order of operations
  339. - = or ==, for strict equality
  340. - <> or !=, for strict inequality
  341. - and or &&, for boolean and
  342. - or or ||, for boolean or
  343. """
  344. gdata.client.Query.__init__(self, **kwargs)
  345. self.order_by = order_by
  346. self.reverse = reverse
  347. self.sq = sq
  348. def modify_request(self, http_request):
  349. gdata.client._add_query_param('orderby', self.order_by, http_request)
  350. gdata.client._add_query_param('reverse', self.reverse, http_request)
  351. gdata.client._add_query_param('sq', self.sq, http_request)
  352. gdata.client.Query.modify_request(self, http_request)
  353. ModifyRequest = modify_request
  354. class TableQuery(ListQuery):
  355. pass
  356. class CellQuery(gdata.client.Query):
  357. def __init__(self, min_row=None, max_row=None, min_col=None, max_col=None,
  358. range=None, return_empty=None, **kwargs):
  359. """Adds Cells-feed specific query parameters to a request.
  360. Args:
  361. min_row: str or int Positional number of minimum row returned in query.
  362. max_row: str or int Positional number of maximum row returned in query.
  363. min_col: str or int Positional number of minimum column returned in query.
  364. max_col: str or int Positional number of maximum column returned in query.
  365. range: str A single cell or a range of cells. Use standard spreadsheet
  366. cell-range notations, using a colon to separate start and end of
  367. range. Examples:
  368. - 'A1' and 'R1C1' both specify only cell A1.
  369. - 'D1:F3' and 'R1C4:R3C6' both specify the rectangle of cells with
  370. corners at D1 and F3.
  371. return_empty: str If 'true' then empty cells will be returned in the feed.
  372. If omitted, the default is 'false'.
  373. """
  374. gdata.client.Query.__init__(self, **kwargs)
  375. self.min_row = min_row
  376. self.max_row = max_row
  377. self.min_col = min_col
  378. self.max_col = max_col
  379. self.range = range
  380. self.return_empty = return_empty
  381. def modify_request(self, http_request):
  382. gdata.client._add_query_param('min-row', self.min_row, http_request)
  383. gdata.client._add_query_param('max-row', self.max_row, http_request)
  384. gdata.client._add_query_param('min-col', self.min_col, http_request)
  385. gdata.client._add_query_param('max-col', self.max_col, http_request)
  386. gdata.client._add_query_param('range', self.range, http_request)
  387. gdata.client._add_query_param('return-empty', self.return_empty,
  388. http_request)
  389. gdata.client.Query.modify_request(self, http_request)
  390. ModifyRequest = modify_request