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.

73 lines
2.3 KiB

  1. from gapi.api import API
  2. import re
  3. APPLICATION_NAME = "Google Calendar API Python"
  4. def is_folder(element):
  5. return element['mimeType'] == 'application/vnd.google-apps.folder'
  6. def split_path(path,rev=False):
  7. s = re.findall(r'(?:^/|[^/\x00]+)',path)
  8. if rev:
  9. return s[::-1]
  10. else:
  11. return s
  12. class drive_api(API):
  13. def __init__(
  14. self,
  15. app_name,
  16. client_secret_file,
  17. credentials_dir,
  18. scopes = 'https://www.googleapis.com/auth/drive',
  19. version = 'v3',
  20. ):
  21. super().__init__('drive',scopes,app_name,client_secret_file,credentials_dir,version)
  22. self.filesystem = {'/':{}}
  23. root_meta = self.service.files().get(fileId='root').execute()
  24. del root_meta['kind']
  25. self.filesystem['/'][0] = root_meta
  26. def get_file_by_path(self,path):
  27. path = split_path(path)
  28. parent = self.filesystem
  29. for sub in path[:-1]:
  30. try:
  31. parent = parent[sub]
  32. except KeyError:
  33. self.fill_in(parent)
  34. parent = parent[sub]
  35. end = path[-1]
  36. for _try in range(2):
  37. try:
  38. return parent[end]
  39. except KeyError:
  40. if _try == 0:
  41. self.fill_in(parent)
  42. else:
  43. raise FileNotFoundError()
  44. # finds all files and folders from a parent
  45. def fill_in(self,parent):
  46. parent_id = parent[0]['id']
  47. child_list = self.list_children(parent_id)
  48. for child in child_list:
  49. del child['kind']
  50. name = child.pop('name')
  51. if is_folder(child):
  52. parent[name] = {}
  53. parent[name][0] = child
  54. else:
  55. parent[name] = child
  56. def list_children(self,parent_id):
  57. page_token = None
  58. first = True
  59. while page_token or first:
  60. first = False
  61. response = self.service.files().list(q = "'{}' in parents".format(parent_id),pageToken=page_token).execute()
  62. page_token = response.get('nextPageToken',None)
  63. for file in response['files']:
  64. yield file
  65. if __name__ == "__main__":
  66. my_api = drive_api(APPLICATION_NAME,r'..\test\drive\client_secret.json',r'..\test\drive')
  67. service = my_api.service