client.py 4.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168
  1. import json
  2. import gspread
  3. from gspread.models import Cell
  4. from oauth2client.service_account import ServiceAccountCredentials
  5. # docs: https://github.com/burnash/gspread
  6. # https://developers.google.com/sheets/api/reference/rest/v4/spreadsheets/sheets#top_of_page
  7. def get_sheet(key, require_write):
  8. scopes = [
  9. 'https://spreadsheets.google.com/feeds',
  10. 'https://www.googleapis.com/auth/drive',
  11. ]
  12. auth = ServiceAccountCredentials.from_json_keyfile_name('gcp-auth.json', scopes)
  13. gc = gspread.authorize(auth)
  14. sheet = gc.open_by_key(key)
  15. try:
  16. permissions = sheet.list_permissions()
  17. if require_write and not [p for p in permissions if p.get('emailAddress') == _get_gcp_user() and p['role'] == 'writer']:
  18. print 'Access control: Bad role. Please ensure that %s has regular write access.' % _get_gcp_user()
  19. return None
  20. return sheet
  21. except gspread.exceptions.APIError, e:
  22. error = json.loads(str(e))['error']
  23. if error['status'] == 'PERMISSION_DENIED':
  24. print 'Access control: Please share the document with %s (write permissions).' % _get_gcp_user()
  25. return None
  26. else:
  27. raise
  28. def _get_gcp_user():
  29. with open('gcp-auth.json') as f:
  30. return json.loads(f.read())['client_email']
  31. def validate_sheet(sheet):
  32. try:
  33. sheet.worksheet('RT config')
  34. sheet.worksheet('RT eval')
  35. except gspread.exceptions.WorksheetNotFound, e:
  36. print 'Sheet not found: "%s"' % e
  37. return False
  38. return True
  39. def get_worksheets(sheet):
  40. return (
  41. sheet.worksheet('RT config'),
  42. sheet.worksheet('RT eval'),
  43. )
  44. def _color(r, g, b):
  45. return {
  46. 'red': r,
  47. 'green': g,
  48. 'blue': b,
  49. }
  50. def _test():
  51. sheet = get_sheet('1JMP9QsXdPbvIVL01LFRAMqkMQZRL17gs_ZjKFBJjI8E', True)
  52. if not sheet:
  53. return
  54. # print 'valid: %s' % validate_sheet(sheet)
  55. ws_config, ws_eval = get_worksheets(sheet)
  56. # data = ws_config.get_all_values()
  57. # cells = []
  58. # for i, row in enumerate(data):
  59. # for j, value in enumerate(row):
  60. # if value:
  61. # cells.append(gspread.models.Cell(i+1, j+1, value))
  62. # ws_eval.update_cells(cells[:10])
  63. cells = []
  64. cells.append(Cell(1, 1, 'SOME TEXT'))
  65. for i in range(50):
  66. cells.append(gspread.models.Cell(3, i+1, i))
  67. ws_eval.update_cells(cells)
  68. print sheet.batch_update({
  69. 'requests': [{
  70. 'updateDimensionProperties': {
  71. 'range': {
  72. 'sheetId': ws_eval.id,
  73. 'dimension': 'COLUMNS',
  74. 'startIndex': 0,
  75. 'endIndex': 1,
  76. },
  77. 'properties': {
  78. 'pixelSize': 200,
  79. },
  80. 'fields': 'pixelSize',
  81. },
  82. }, {
  83. 'updateDimensionProperties': {
  84. 'range': {
  85. 'sheetId': ws_eval.id,
  86. 'dimension': 'COLUMNS',
  87. 'startIndex': 1,
  88. 'endIndex': 50,
  89. },
  90. 'properties': {
  91. 'pixelSize': 21,
  92. },
  93. 'fields': 'pixelSize',
  94. },
  95. }],
  96. })
  97. print sheet.batch_update({
  98. 'requests': [{
  99. 'updateDimensionProperties': {
  100. 'range': {
  101. 'sheetId': ws_eval.id,
  102. 'dimension': 'ROWS',
  103. 'startIndex': 0,
  104. 'endIndex': 1000,
  105. },
  106. 'properties': {
  107. 'pixelSize': 21,
  108. },
  109. 'fields': 'pixelSize',
  110. },
  111. }],
  112. })
  113. import random
  114. xs = []
  115. for i in range(50):
  116. xs.append({
  117. 'userEnteredFormat': {
  118. 'backgroundColor': _color(1, i/50., i/50.)
  119. # 'backgroundColor': _color(random.random(), random.random(), random.random())
  120. }
  121. })
  122. print sheet.batch_update({
  123. 'requests': [{
  124. 'updateCells': {
  125. 'rows': [{
  126. 'values': xs,
  127. }],
  128. 'fields': 'userEnteredFormat.backgroundColor',
  129. 'start': {
  130. 'sheetId': ws_eval.id,
  131. 'rowIndex': 0,
  132. 'columnIndex': 0,
  133. }
  134. }
  135. }]
  136. })
  137. # _test()