| 1 |
# -*- coding: utf-8 -*- |
| 2 |
from __future__ import absolute_import, print_function, division |
| 3 |
|
| 4 |
from petl.util.base import Table, iterdata |
| 5 |
from petl.compat import text_type |
| 6 |
from petl.errors import ArgumentError as PetlArgError |
| 7 |
|
| 8 |
|
| 9 |
def _get_gspread_client(auth_info): |
| 10 |
import gspread |
| 11 |
|
| 12 |
if isinstance(auth_info, gspread.Client): |
| 13 |
return auth_info |
| 14 |
if isinstance(auth_info, dict): |
| 15 |
gd = gspread.service_account_from_dict(auth_info) |
| 16 |
return gd |
| 17 |
import google |
| 18 |
|
| 19 |
if isinstance(auth_info, google.oauth2.service_account.Credentials): |
| 20 |
gc = gspread.authorize(auth_info) |
| 21 |
return gc |
| 22 |
if auth_info is None: |
| 23 |
ga = gspread.service_account() |
| 24 |
return ga |
| 25 |
raise PetlArgError("gspread: Invalid account credentials") |
| 26 |
|
| 27 |
|
| 28 |
def _open_spreadsheet(gspread_client, spreadsheet, open_by_key=False): |
| 29 |
if open_by_key: |
| 30 |
from gspread.exceptions import SpreadsheetNotFound |
| 31 |
try: |
| 32 |
wb = gspread_client.open_by_key(spreadsheet) |
| 33 |
except SpreadsheetNotFound: |
| 34 |
wb = gspread_client.open(spreadsheet) |
| 35 |
elif spreadsheet is not None: |
| 36 |
wb = gspread_client.open(spreadsheet) |
| 37 |
else: |
| 38 |
raise PetlArgError("gspread requires argument spreadsheet") |
| 39 |
return wb |
| 40 |
|
| 41 |
|
| 42 |
def _select_worksheet(wb, worksheet, find_or_create=False): |
| 43 |
# Allow for user to specify no sheet, sheet index or sheet name |
| 44 |
if worksheet is None: |
| 45 |
ws = wb.sheet1 |
| 46 |
elif isinstance(worksheet, int): |
| 47 |
ws = wb.get_worksheet(worksheet) |
| 48 |
elif isinstance(worksheet, text_type): |
| 49 |
sheetname = text_type(worksheet) |
| 50 |
if find_or_create: |
| 51 |
if worksheet in [wbs.title for wbs in wb.worksheets()]: |
| 52 |
ws = wb.worksheet(sheetname) |
| 53 |
else: |
| 54 |
ws = wb.add_worksheet(sheetname, 1, 1) |
| 55 |
else: |
| 56 |
# use text_type for cross version compatibility |
| 57 |
ws = wb.worksheet(sheetname) |
| 58 |
else: |
| 59 |
raise PetlArgError("Only can find worksheet by name or by number") |
| 60 |
return ws |
| 61 |
|
| 62 |
|
| 63 |
def fromgsheet( |
| 64 |
credentials_or_client, spreadsheet, worksheet=None, cell_range=None, |
| 65 |
open_by_key=False |
| 66 |
): |
| 67 |
""" |
| 68 |
Extract a table from a google spreadsheet. |
| 69 |
|
| 70 |
The `credentials_or_client` are used to authenticate with the google apis. |
| 71 |
For more info, check `authentication`_. |
| 72 |
|
| 73 |
The `spreadsheet` can either be the key of the spreadsheet or its name. |
| 74 |
|
| 75 |
The `worksheet` argument can be omitted, in which case the first |
| 76 |
sheet in the workbook is used by default. |
| 77 |
|
| 78 |
The `cell_range` argument can be used to provide a range string |
| 79 |
specifying the top left and bottom right corners of a set of cells to |
| 80 |
extract. (i.e. 'A1:C7'). |
| 81 |
|
| 82 |
Set `open_by_key` to `True` in order to treat `spreadsheet` as spreadsheet key. |
| 83 |
|
| 84 |
.. note:: |
| 85 |
- Only the top level of google drive will be searched for the |
| 86 |
spreadsheet filename due to API limitations. |
| 87 |
- The worksheet name is case sensitive. |
| 88 |
|
| 89 |
Example usage follows:: |
| 90 |
|
| 91 |
>>> from petl import fromgsheet |
| 92 |
>>> import gspread # doctest: +SKIP |
| 93 |
>>> client = gspread.service_account() # doctest: +SKIP |
| 94 |
>>> tbl1 = fromgsheet(client, 'example_spreadsheet', 'Sheet1') # doctest: +SKIP |
| 95 |
>>> tbl2 = fromgsheet(client, '9zDNETemfau0uY8ZJF0YzXEPB_5GQ75JV', credentials) # doctest: +SKIP |
| 96 |
|
| 97 |
This functionality relies heavily on the work by @burnash and his great |
| 98 |
`gspread module`_. |
| 99 |
|
| 100 |
.. _gspread module: http://gspread.readthedocs.io/ |
| 101 |
.. _authentication: http://gspread.readthedocs.io/en/latest/oauth2.html |
| 102 |
""" |
| 103 |
|
| 104 |
return GoogleSheetView( |
| 105 |
credentials_or_client, |
| 106 |
spreadsheet, |
| 107 |
worksheet, |
| 108 |
cell_range, |
| 109 |
open_by_key, |
| 110 |
) |
| 111 |
|
| 112 |
|
| 113 |
class GoogleSheetView(Table): |
| 114 |
"""Conects to a worksheet and iterates over its rows.""" |
| 115 |
|
| 116 |
def __init__( |
| 117 |
self, credentials_or_client, spreadsheet, worksheet, cell_range, |
| 118 |
open_by_key |
| 119 |
): |
| 120 |
self.auth_info = credentials_or_client |
| 121 |
self.spreadsheet = spreadsheet |
| 122 |
self.worksheet = worksheet |
| 123 |
self.cell_range = cell_range |
| 124 |
self.open_by_key = open_by_key |
| 125 |
|
| 126 |
def __iter__(self): |
| 127 |
gspread_client = _get_gspread_client(self.auth_info) |
| 128 |
wb = _open_spreadsheet(gspread_client, self.spreadsheet, self.open_by_key) |
| 129 |
ws = _select_worksheet(wb, self.worksheet) |
| 130 |
# grab the range or grab the whole sheet |
| 131 |
if self.cell_range is not None: |
| 132 |
return self._yield_by_range(ws) |
| 133 |
return self._yield_all_rows(ws) |
| 134 |
|
| 135 |
def _yield_all_rows(self, ws): |
| 136 |
# no range specified, so return all the rows |
| 137 |
for row in ws.get_all_values(): |
| 138 |
yield tuple(row) |
| 139 |
|
| 140 |
def _yield_by_range(self, ws): |
| 141 |
found = ws.get_values(self.cell_range) |
| 142 |
for row in found: |
| 143 |
yield tuple(row) |
| 144 |
|
| 145 |
|
| 146 |
def togsheet( |
| 147 |
table, credentials_or_client, spreadsheet, worksheet=None, cell_range=None, |
| 148 |
share_emails=None, role="reader" |
| 149 |
): |
| 150 |
""" |
| 151 |
Write a table to a new google sheet. |
| 152 |
|
| 153 |
The `credentials_or_client` are used to authenticate with the google apis. |
| 154 |
For more info, check `authentication`_. |
| 155 |
|
| 156 |
The `spreadsheet` will be the title of the workbook created google sheets. |
| 157 |
If there is a spreadsheet with same title a new one will be created. |
| 158 |
|
| 159 |
If `worksheet` is specified, the first worksheet in the spreadsheet |
| 160 |
will be renamed to its value. |
| 161 |
|
| 162 |
The spreadsheet will be shared with all emails in `share_emails` with |
| 163 |
`role` permissions granted. For more info, check `sharing`_. |
| 164 |
|
| 165 |
Returns: the spreadsheet key that can be used in `appendgsheet` further. |
| 166 |
|
| 167 |
|
| 168 |
.. _sharing: https://developers.google.com/drive/v3/web/manage-sharing |
| 169 |
|
| 170 |
.. note:: |
| 171 |
The `gspread`_ package doesn't support serialization of `date` and |
| 172 |
`datetime` types yet. |
| 173 |
|
| 174 |
Example usage:: |
| 175 |
|
| 176 |
>>> from petl import fromcolumns, togsheet |
| 177 |
>>> import gspread # doctest: +SKIP |
| 178 |
>>> client = gspread.service_account() # doctest: +SKIP |
| 179 |
>>> cols = [[0, 1, 2], ['a', 'b', 'c']] |
| 180 |
>>> tbl = fromcolumns(cols) |
| 181 |
>>> togsheet(tbl, client, 'example_spreadsheet') # doctest: +SKIP |
| 182 |
""" |
| 183 |
|
| 184 |
gspread_client = _get_gspread_client(credentials_or_client) |
| 185 |
wb = gspread_client.create(spreadsheet) |
| 186 |
ws = wb.sheet1 |
| 187 |
ws.resize(rows=1, cols=1) # make smallest table possible |
| 188 |
# rename sheet if set |
| 189 |
if worksheet is not None: |
| 190 |
ws.update_title(title=worksheet) |
| 191 |
# gspread indices start at 1, therefore row index insert starts at 1 |
| 192 |
ws.append_rows(table, table_range=cell_range) |
| 193 |
# specify the user account to share to |
| 194 |
if share_emails is not None: |
| 195 |
for user_email in share_emails: |
| 196 |
wb.share(user_email, perm_type="user", role=role) |
| 197 |
return wb.id |
| 198 |
|
| 199 |
|
| 200 |
def appendgsheet( |
| 201 |
table, credentials_or_client, spreadsheet, worksheet=None, |
| 202 |
open_by_key=False, include_header=False |
| 203 |
): |
| 204 |
""" |
| 205 |
Append a table to an existing google shoot at either a new worksheet |
| 206 |
or the end of an existing worksheet. |
| 207 |
|
| 208 |
The `credentials_or_client` are used to authenticate with the google apis. |
| 209 |
For more info, check `authentication`_. |
| 210 |
|
| 211 |
The `spreadsheet` is the name of the workbook to append to. |
| 212 |
|
| 213 |
The `worksheet` is the title of the worksheet to append to or create when it |
| 214 |
does not exist yet. |
| 215 |
|
| 216 |
Set `open_by_key` to `True` in order to treat `spreadsheet` as spreadsheet key. |
| 217 |
|
| 218 |
Set `include_header` to `True` if you don't want omit fieldnames as the |
| 219 |
first row appended. |
| 220 |
|
| 221 |
.. note:: |
| 222 |
The sheet index cannot be used, and None is not an option. |
| 223 |
""" |
| 224 |
gspread_client = _get_gspread_client(credentials_or_client) |
| 225 |
# be able to give filename or key for file |
| 226 |
wb = _open_spreadsheet(gspread_client, spreadsheet, open_by_key) |
| 227 |
# check to see if worksheet exists, if so append, otherwise create |
| 228 |
ws = _select_worksheet(wb, worksheet, True) |
| 229 |
rows = table if include_header else list(iterdata(table)) |
| 230 |
ws.append_rows(rows) |
| 231 |
return wb.id |
| 232 |
|
| 233 |
|
| 234 |
Table.togsheet = togsheet |
| 235 |
Table.appendgsheet = appendgsheet |