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. from apiclient import discovery
  2. import datetime
  3. from googleapiclient.discovery import build
  4. from googleapiclient.errors import HttpError
  5. from oauth2client import client
  6. from oauth2client import tools
  7. from oauth2client.file import Storage
  8. from oauth2client.service_account import ServiceAccountCredentials
  9. import httplib2
  10. import os
  11. import argparse
  12. flags = argparse.ArgumentParser(parents=[tools.argparser]).parse_args()
  13. class api:
  14. def __init__(
  15. self,
  16. service,
  17. scopes,
  18. app_name,
  19. client_secret_file,
  20. credentials_dir,
  21. version = '3',
  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. 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 = APPLICATION_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