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
73 lines
2.3 KiB
from gapi.api import API
|
|
import re
|
|
APPLICATION_NAME = "Google Calendar API Python"
|
|
def is_folder(element):
|
|
return element['mimeType'] == 'application/vnd.google-apps.folder'
|
|
def split_path(path,rev=False):
|
|
|
|
s = re.findall(r'(?:^/|[^/\x00]+)',path)
|
|
if rev:
|
|
return s[::-1]
|
|
else:
|
|
return s
|
|
|
|
class drive_api(API):
|
|
def __init__(
|
|
self,
|
|
app_name,
|
|
client_secret_file,
|
|
credentials_dir,
|
|
scopes = 'https://www.googleapis.com/auth/drive',
|
|
version = 'v3',
|
|
):
|
|
super().__init__('drive',scopes,app_name,client_secret_file,credentials_dir,version)
|
|
self.filesystem = {'/':{}}
|
|
root_meta = self.service.files().get(fileId='root').execute()
|
|
del root_meta['kind']
|
|
self.filesystem['/'][0] = root_meta
|
|
|
|
def get_file_by_path(self,path):
|
|
path = split_path(path)
|
|
parent = self.filesystem
|
|
for sub in path[:-1]:
|
|
try:
|
|
parent = parent[sub]
|
|
except KeyError:
|
|
self.fill_in(parent)
|
|
parent = parent[sub]
|
|
end = path[-1]
|
|
try:
|
|
return parent[end]
|
|
except KeyError:
|
|
self.fill_in(parent)
|
|
try:
|
|
return parent[end]
|
|
except KeyError:
|
|
raise FileNotFoundError()
|
|
|
|
# finds all files and folders from a parent
|
|
def fill_in(self,parent):
|
|
parent_id = parent[0]['id']
|
|
child_list = self.list_children(parent_id)
|
|
for child in child_list:
|
|
del child['kind']
|
|
name = child.pop('name')
|
|
if is_folder(child):
|
|
parent[name] = {}
|
|
parent[name][0] = child
|
|
else:
|
|
parent[name] = child
|
|
|
|
def list_children(self,parent_id):
|
|
page_token = None
|
|
first = True
|
|
while page_token or first:
|
|
first = False
|
|
response = self.service.files().list(q = "'{}' in parents".format(parent_id),pageToken=page_token).execute()
|
|
page_token = response.get('nextPageToken',None)
|
|
for file in response['files']:
|
|
yield file
|
|
|
|
if __name__ == "__main__":
|
|
my_api = drive_api(APPLICATION_NAME,r'..\test\drive\client_secret.json',r'..\test\drive')
|
|
service = my_api.service
|