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.

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