-
Notifications
You must be signed in to change notification settings - Fork 0
/
utils.py
65 lines (58 loc) · 1.88 KB
/
utils.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
import json
import requests
from fastapi import UploadFile
from pydrive2.auth import GoogleAuth
from pydrive2.drive import GoogleDrive
def search_file_in_drive_or_none(
drive: GoogleDrive, key: str, folder_id: str
) -> GoogleDrive:
file_list = drive.ListFile(
{"q": f"'{folder_id}' in parents and trashed=false"}
).GetList()
for file in file_list:
if key == file["title"]:
return file
def upload_to_google_drive(
drive: GoogleDrive, g_auth: GoogleAuth, data: UploadFile, folder_id: str
) -> json:
key = data.filename
value = data.file
metadata = {
"name": f"{key}",
"parents": [folder_id],
}
files = {
"data": ("metadata", json.dumps(metadata), "application/json"),
"file": value,
}
file = search_file_in_drive_or_none(drive=drive, key=key, folder_id=folder_id)
if file is not None:
file_id = f"{file['id']}"
response = requests.put(
f"https://www.googleapis.com/upload/drive/v2/files/{file_id}?uploadType=multipart",
headers={"Authorization": "Bearer " + g_auth.credentials.access_token},
files=files,
)
else:
response = requests.post(
"https://www.googleapis.com/upload/drive/v3/files?uploadType=multipart",
headers={"Authorization": "Bearer " + g_auth.credentials.access_token},
files=files,
)
return {
"Status code": response.status_code,
"Key": key,
}
def get_file_for_key(drive: GoogleDrive, key: str, folder_id: str) -> json:
file = search_file_in_drive_or_none(drive=drive, key=key, folder_id=folder_id)
if file is not None:
file.GetContentFile(file["title"])
return {
"Key": key,
"Status": "Download",
}
else:
return {
"Key": key,
"Status": "Not found",
}