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.

78 lines
2.5 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 __inner_path_func__(self,path,parent):
  27. print(path)
  28. if len(path) > 1:
  29. n = path.pop()
  30. try:
  31. new_parent = parent[n]
  32. except KeyError:
  33. self.fill_in(parent)
  34. new_parent = parent[n]
  35. return self.__inner_path_func__(path,new_parent)
  36. else:
  37. try:
  38. return parent[path[0]]
  39. except KeyError:
  40. self.fill_in(parent)
  41. try:
  42. return parent[path[0]]
  43. except KeyError:
  44. raise FileNotFoundError()
  45. def get_file_by_path(self,path):
  46. path = split_path(path,True)
  47. return self.__inner_path_func__(path,self.filesystem)
  48. # finds all files and folders from a parent
  49. def fill_in(self,parent):
  50. parent_id = parent[0]['id']
  51. child_list = self.list_children(parent_id)
  52. for child in child_list:
  53. del child['kind']
  54. name = child.pop('name')
  55. if is_folder(child):
  56. parent[name] = {}
  57. parent[name][0] = child
  58. else:
  59. parent[name] = child
  60. def list_children(self,parent_id):
  61. page_token = None
  62. first = True
  63. while page_token or first:
  64. first = False
  65. response = self.service.files().list(q = "'{}' in parents".format(parent_id),pageToken=page_token).execute()
  66. page_token = response.get('nextPageToken',None)
  67. for file in response['files']:
  68. yield file
  69. if __name__ == "__main__":
  70. my_api = drive_api(APPLICATION_NAME,r'..\test\drive\client_secret.json',r'..\test\drive')
  71. service = my_api.service