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.

75 lines
2.3 KiB

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