You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

81 lines
2.3 KiB

  1. import datetime
  2. from googleapiclient.discovery import build
  3. from googleapiclient.errors import *
  4. from oauth2client import client
  5. from oauth2client import tools
  6. from oauth2client.file import Storage
  7. # from oauth2client.service_account import ServiceAccountCredentials
  8. import httplib2
  9. import os
  10. import argparse
  11. flags = argparse.ArgumentParser(parents=[tools.argparser]).parse_args()
  12. HOUR = datetime.timedelta(seconds=60**2)
  13. class API:
  14. def __init__(
  15. self,
  16. service,
  17. scopes,
  18. app_name,
  19. client_secret_file,
  20. credentials_dir,
  21. version='v3',
  22. ):
  23. self.service_name = service
  24. self.app_name = app_name
  25. self.client_secret_file = client_secret_file
  26. self.credentials_dir = credentials_dir
  27. self.scopes = scopes
  28. self._service = None
  29. self._service_settime = None
  30. self.version = version
  31. def get_credentials(self):
  32. credential_path = os.path.join(self.credentials_dir,
  33. 'token.json')
  34. store = Storage(credential_path)
  35. credentials = store.get()
  36. if not credentials or credentials.invalid:
  37. flow = client.flow_from_clientsecrets(
  38. self.client_secret_file, self.scopes)
  39. flow.user_agent = self.app_name
  40. if flags:
  41. credentials = tools.run_flow(flow, store, flags)
  42. else:
  43. credentials = tools.run(flow, store)
  44. print('Storing credentials to ' + credential_path)
  45. return credentials
  46. def build_service(self):
  47. credentials = self.get_credentials()
  48. http = credentials.authorize(httplib2.Http())
  49. service = build(self.service_name, self.version,
  50. http=http, cache_discovery=False)
  51. return service
  52. def _needs_renewal(self):
  53. now = datetime.datetime.today()
  54. if self._service_settime:
  55. return (now - self._service_settime) > HOUR
  56. else:
  57. return True
  58. @property
  59. def service(self):
  60. if self._needs_renewal():
  61. service = self.build_service()
  62. self._service = service
  63. self._service_settime = datetime.datetime.today()
  64. return service
  65. else:
  66. return self._service