Saya sedang mengerjakan pengarsipan otomatis yang ditulis dengan Python. menjelaskan bagaimana kita bisa mendapatkan Service Account setup untuk membaca dan menulis ke lembar
Mari kita lihat menghubungkan ke Google Drive melalui
- Akun Layanan (seperti yang saya lakukan dengan Google Sheet) - tidak menggunakan ini pada batas unggahan 15GB dan masalah kepemilikan file
- OAuth2 - Publikasikan Pengujian Status bukan akun Workspace (yaitu eksternal), token kedaluwarsa setelah 1 minggu
- OAuth2 - Publikasikan Pengujian Status, akun Workspace (yaitu internal), token kedaluwarsa setelah ?
- OAuth2 - Publikasikan Status Dipublikasikan, token akun non Workspace (yaitu eksternal) kedaluwarsa setelah ?
1. Akun Layanan
https. //blog. benjames. io/2020/09/13/otorisasi-your-python-google-drive-api-the-easy-way/
Dari tautan di atas jadi kami memiliki service_account.json
https. //menghibur. awan. google. com/ Konsol Pengembang Google, API, Kredensial
Perpustakaan Klien Python
https. // pengembang. google. com/drive/api/quickstart/python - dari sini Anda dapat menjelajahi API
from google.oauth2 import service_account from googleapiclient.discovery import build SCOPES = ['//www.googleapis.com/auth/drive'] creds = service_account.Credentials.from_service_account_file('service_account.json', scopes=SCOPES) service = build('drive', 'v3', credentials=creds) # 1. Call the Drive v3 API to get files results = service.files().list().execute() items = results.get('files', []) for item in items: print(u'{0} ({1})'.format(item['name'], item['id']))
https. //github. com/djhmateer/auto-archiver/blob/main/dm_drive2. py lebih banyak contoh kode untuk mengunggah, mencari file, mencari folder, membuat folder
Bagikan folder dengan akun layanan misalnya autoarchiverservice@auto-archiver-xxxxx.iam.gserviceaccount.com
Ini memungkinkan saya untuk membaca dan menulis ke folder bersama di akun google drive (dalam hal ini adalah google drive pribadi saya) dari akun layanan
yaitu saya dapat melihat folder_id bersama saya kemudian dapat menulis di dalam folder itu
Batas 15GB pada Akun Layanan
Ini mengejutkan
Penyimpanan dihitung terhadap orang yang mengunggah file, bukan pemilik folder
Jadi folder yang dishare (yang kuotanya 100GB) tiba-tiba error
Kuota penyimpanan Drive pengguna telah terlampaui
Itu adalah akun layanan gratis penyimpanan 15GB yang telah terlampaui
https. //stackoverflow. com/a/68313988/26086
Kepemilikan File
Saya ingin pemilik folder bersama target menjadi pemilik file yang saya unggah. Ini rumit. Jadi mari kita lihat apa yang dapat dilakukan dengan ID klien OAuth
2. OAuth dengan Publish Status Testing dan External non Workspace User
https. // pengembang. google. com/drive/api/quickstart/python Quickstart untuk API memandu Anda menyusuri rute OAuth (dan bukan akun layanan)
- Saya memiliki proyek dengan API Drive yang diaktifkan di bawah pengguna tertentu (davemateer@gmail. com)
- Kredensial otorisasi untuk aplikasi Desktop Buat Kredensial Akses
Layar Persetujuan
Perlu melakukan ini sebelum membuat OAuthID
- Intern. Hanya untuk pelanggan Google Workspace. Hanya tersedia untuk pengguna dalam organisasi Anda. Tidak perlu mengirimkan aplikasi untuk verifikasi
- Luar. Aplikasi akan dimulai dalam mode pengujian, dan hanya tersedia untuk pengguna yang Anda tambahkan ke daftar pengguna pengujian
Pilih Eksternal, tambahkan Judul (Pengarsip Otomatis) dan alamat email kontak dan dev (davemateer@gmail. com)
Cakupan - tidak ada
Pengguna uji - Saya telah menambahkan akun uji terpisah tanpa file di drive-nya (greenbranflakes@gmail. com)
Buat ID OAuth
Nama. Auto-Archiver-Alpha (nama tidak akan ditampilkan ke pengguna akhir)
Dapat mengunduh client_secret.json atau from __future__ import print_function import os.path from google.auth.transport.requests import Request from google.oauth2.credentials import Credentials from google_auth_oauthlib.flow import InstalledAppFlow from googleapiclient.discovery import build from googleapiclient.errors import HttpError from googleapiclient.http import MediaFileUpload # If modifying these scopes, delete the file token.json. SCOPES = ['//www.googleapis.com/auth/drive'] def main(): """Shows basic usage of the Drive v3 API. Prints the names and ids of the first 10 files the user has access to. """ token_file = 'gd-token.json' creds = None # The file token.json stores the user's access and refresh tokens, and is # created automatically when the authorization flow completes for the first # time. if os.path.exists(token_file): creds = Credentials.from_authorized_user_file(token_file, SCOPES) # If there are no (valid) credentials available, let the user log in. if not creds or not creds.valid: if creds and creds.expired and creds.refresh_token: print('Requesting new token') creds.refresh(Request()) else: print('First run through so putting up login dialog') # credentials.json downloaded from //console.cloud.google.com/apis/credentials flow = InstalledAppFlow.from_client_secrets_file( 'credentials.json', SCOPES) creds = flow.run_local_server(port=0) # Save the credentials for the next run with open(token_file, 'w') as token: print('Saving new token') print('') token.write(creds.to_json()) else: print('Token valid') try: service = build('drive', 'v3', credentials=creds) # 0. About the user results = service.about().get(fields="*").execute() emailAddress = results['user']['emailAddress'] print(emailAddress) # 1. Call the Drive v3 API results = service.files().list( pageSize=10, fields="nextPageToken, files(id, name)").execute() items = results.get('files', []) if not items: print('No files found.') return print('Files:') for item in items: print(u'{0} ({1})'.format(item['name'], item['id'])) except HttpError as error: # TODO(developer) - Handle errors from drive API. print(f'An error occurred: {error}') if __name__ == '__main__': main() 0 (inilah yang disebut sampel kode)
- ID Klien misalnya from __future__ import print_function import os.path from google.auth.transport.requests import Request from google.oauth2.credentials import Credentials from google_auth_oauthlib.flow import InstalledAppFlow from googleapiclient.discovery import build from googleapiclient.errors import HttpError from googleapiclient.http import MediaFileUpload # If modifying these scopes, delete the file token.json. SCOPES = ['//www.googleapis.com/auth/drive'] def main(): """Shows basic usage of the Drive v3 API. Prints the names and ids of the first 10 files the user has access to. """ token_file = 'gd-token.json' creds = None # The file token.json stores the user's access and refresh tokens, and is # created automatically when the authorization flow completes for the first # time. if os.path.exists(token_file): creds = Credentials.from_authorized_user_file(token_file, SCOPES) # If there are no (valid) credentials available, let the user log in. if not creds or not creds.valid: if creds and creds.expired and creds.refresh_token: print('Requesting new token') creds.refresh(Request()) else: print('First run through so putting up login dialog') # credentials.json downloaded from //console.cloud.google.com/apis/credentials flow = InstalledAppFlow.from_client_secrets_file( 'credentials.json', SCOPES) creds = flow.run_local_server(port=0) # Save the credentials for the next run with open(token_file, 'w') as token: print('Saving new token') print('') token.write(creds.to_json()) else: print('Token valid') try: service = build('drive', 'v3', credentials=creds) # 0. About the user results = service.about().get(fields="*").execute() emailAddress = results['user']['emailAddress'] print(emailAddress) # 1. Call the Drive v3 API results = service.files().list( pageSize=10, fields="nextPageToken, files(id, name)").execute() items = results.get('files', []) if not items: print('No files found.') return print('Files:') for item in items: print(u'{0} ({1})'.format(item['name'], item['id'])) except HttpError as error: # TODO(developer) - Handle errors from drive API. print(f'An error occurred: {error}') if __name__ == '__main__': main() 1
- Rahasia Klien misalnya from __future__ import print_function import os.path from google.auth.transport.requests import Request from google.oauth2.credentials import Credentials from google_auth_oauthlib.flow import InstalledAppFlow from googleapiclient.discovery import build from googleapiclient.errors import HttpError from googleapiclient.http import MediaFileUpload # If modifying these scopes, delete the file token.json. SCOPES = ['//www.googleapis.com/auth/drive'] def main(): """Shows basic usage of the Drive v3 API. Prints the names and ids of the first 10 files the user has access to. """ token_file = 'gd-token.json' creds = None # The file token.json stores the user's access and refresh tokens, and is # created automatically when the authorization flow completes for the first # time. if os.path.exists(token_file): creds = Credentials.from_authorized_user_file(token_file, SCOPES) # If there are no (valid) credentials available, let the user log in. if not creds or not creds.valid: if creds and creds.expired and creds.refresh_token: print('Requesting new token') creds.refresh(Request()) else: print('First run through so putting up login dialog') # credentials.json downloaded from //console.cloud.google.com/apis/credentials flow = InstalledAppFlow.from_client_secrets_file( 'credentials.json', SCOPES) creds = flow.run_local_server(port=0) # Save the credentials for the next run with open(token_file, 'w') as token: print('Saving new token') print('') token.write(creds.to_json()) else: print('Token valid') try: service = build('drive', 'v3', credentials=creds) # 0. About the user results = service.about().get(fields="*").execute() emailAddress = results['user']['emailAddress'] print(emailAddress) # 1. Call the Drive v3 API results = service.files().list( pageSize=10, fields="nextPageToken, files(id, name)").execute() items = results.get('files', []) if not items: print('No files found.') return print('Files:') for item in items: print(u'{0} ({1})'.format(item['name'], item['id'])) except HttpError as error: # TODO(developer) - Handle errors from drive API. print(f'An error occurred: {error}') if __name__ == '__main__': main() 2
Ini dibatasi untuk pengguna uji yang ditambahkan di atas
Kode
https. // pengembang. google. com/drive/api/quickstart/python dari kode di sini
from __future__ import print_function import os.path from google.auth.transport.requests import Request from google.oauth2.credentials import Credentials from google_auth_oauthlib.flow import InstalledAppFlow from googleapiclient.discovery import build from googleapiclient.errors import HttpError from googleapiclient.http import MediaFileUpload # If modifying these scopes, delete the file token.json. SCOPES = ['//www.googleapis.com/auth/drive'] def main(): """Shows basic usage of the Drive v3 API. Prints the names and ids of the first 10 files the user has access to. """ token_file = 'gd-token.json' creds = None # The file token.json stores the user's access and refresh tokens, and is # created automatically when the authorization flow completes for the first # time. if os.path.exists(token_file): creds = Credentials.from_authorized_user_file(token_file, SCOPES) # If there are no (valid) credentials available, let the user log in. if not creds or not creds.valid: if creds and creds.expired and creds.refresh_token: print('Requesting new token') creds.refresh(Request()) else: print('First run through so putting up login dialog') # credentials.json downloaded from //console.cloud.google.com/apis/credentials flow = InstalledAppFlow.from_client_secrets_file( 'credentials.json', SCOPES) creds = flow.run_local_server(port=0) # Save the credentials for the next run with open(token_file, 'w') as token: print('Saving new token') print('') token.write(creds.to_json()) else: print('Token valid') try: service = build('drive', 'v3', credentials=creds) # 0. About the user results = service.about().get(fields="*").execute() emailAddress = results['user']['emailAddress'] print(emailAddress) # 1. Call the Drive v3 API results = service.files().list( pageSize=10, fields="nextPageToken, files(id, name)").execute() items = results.get('files', []) if not items: print('No files found.') return print('Files:') for item in items: print(u'{0} ({1})'.format(item['name'], item['id'])) except HttpError as error: # TODO(developer) - Handle errors from drive API. print(f'An error occurred: {error}') if __name__ == '__main__': main() 3 menyimpan akses pengguna from __future__ import print_function import os.path from google.auth.transport.requests import Request from google.oauth2.credentials import Credentials from google_auth_oauthlib.flow import InstalledAppFlow from googleapiclient.discovery import build from googleapiclient.errors import HttpError from googleapiclient.http import MediaFileUpload # If modifying these scopes, delete the file token.json. SCOPES = ['//www.googleapis.com/auth/drive'] def main(): """Shows basic usage of the Drive v3 API. Prints the names and ids of the first 10 files the user has access to. """ token_file = 'gd-token.json' creds = None # The file token.json stores the user's access and refresh tokens, and is # created automatically when the authorization flow completes for the first # time. if os.path.exists(token_file): creds = Credentials.from_authorized_user_file(token_file, SCOPES) # If there are no (valid) credentials available, let the user log in. if not creds or not creds.valid: if creds and creds.expired and creds.refresh_token: print('Requesting new token') creds.refresh(Request()) else: print('First run through so putting up login dialog') # credentials.json downloaded from //console.cloud.google.com/apis/credentials flow = InstalledAppFlow.from_client_secrets_file( 'credentials.json', SCOPES) creds = flow.run_local_server(port=0) # Save the credentials for the next run with open(token_file, 'w') as token: print('Saving new token') print('') token.write(creds.to_json()) else: print('Token valid') try: service = build('drive', 'v3', credentials=creds) # 0. About the user results = service.about().get(fields="*").execute() emailAddress = results['user']['emailAddress'] print(emailAddress) # 1. Call the Drive v3 API results = service.files().list( pageSize=10, fields="nextPageToken, files(id, name)").execute() items = results.get('files', []) if not items: print('No files found.') return print('Files:') for item in items: print(u'{0} ({1})'.format(item['name'], item['id'])) except HttpError as error: # TODO(developer) - Handle errors from drive API. print(f'An error occurred: {error}') if __name__ == '__main__': main() 4 dan from __future__ import print_function import os.path from google.auth.transport.requests import Request from google.oauth2.credentials import Credentials from google_auth_oauthlib.flow import InstalledAppFlow from googleapiclient.discovery import build from googleapiclient.errors import HttpError from googleapiclient.http import MediaFileUpload # If modifying these scopes, delete the file token.json. SCOPES = ['//www.googleapis.com/auth/drive'] def main(): """Shows basic usage of the Drive v3 API. Prints the names and ids of the first 10 files the user has access to. """ token_file = 'gd-token.json' creds = None # The file token.json stores the user's access and refresh tokens, and is # created automatically when the authorization flow completes for the first # time. if os.path.exists(token_file): creds = Credentials.from_authorized_user_file(token_file, SCOPES) # If there are no (valid) credentials available, let the user log in. if not creds or not creds.valid: if creds and creds.expired and creds.refresh_token: print('Requesting new token') creds.refresh(Request()) else: print('First run through so putting up login dialog') # credentials.json downloaded from //console.cloud.google.com/apis/credentials flow = InstalledAppFlow.from_client_secrets_file( 'credentials.json', SCOPES) creds = flow.run_local_server(port=0) # Save the credentials for the next run with open(token_file, 'w') as token: print('Saving new token') print('') token.write(creds.to_json()) else: print('Token valid') try: service = build('drive', 'v3', credentials=creds) # 0. About the user results = service.about().get(fields="*").execute() emailAddress = results['user']['emailAddress'] print(emailAddress) # 1. Call the Drive v3 API results = service.files().list( pageSize=10, fields="nextPageToken, files(id, name)").execute() items = results.get('files', []) if not items: print('No files found.') return print('Files:') for item in items: print(u'{0} ({1})'.format(item['name'], item['id'])) except HttpError as error: # TODO(developer) - Handle errors from drive API. print(f'An error occurred: {error}') if __name__ == '__main__': main() 5 dan juga mencakup from __future__ import print_function import os.path from google.auth.transport.requests import Request from google.oauth2.credentials import Credentials from google_auth_oauthlib.flow import InstalledAppFlow from googleapiclient.discovery import build from googleapiclient.errors import HttpError from googleapiclient.http import MediaFileUpload # If modifying these scopes, delete the file token.json. SCOPES = ['//www.googleapis.com/auth/drive'] def main(): """Shows basic usage of the Drive v3 API. Prints the names and ids of the first 10 files the user has access to. """ token_file = 'gd-token.json' creds = None # The file token.json stores the user's access and refresh tokens, and is # created automatically when the authorization flow completes for the first # time. if os.path.exists(token_file): creds = Credentials.from_authorized_user_file(token_file, SCOPES) # If there are no (valid) credentials available, let the user log in. if not creds or not creds.valid: if creds and creds.expired and creds.refresh_token: print('Requesting new token') creds.refresh(Request()) else: print('First run through so putting up login dialog') # credentials.json downloaded from //console.cloud.google.com/apis/credentials flow = InstalledAppFlow.from_client_secrets_file( 'credentials.json', SCOPES) creds = flow.run_local_server(port=0) # Save the credentials for the next run with open(token_file, 'w') as token: print('Saving new token') print('') token.write(creds.to_json()) else: print('Token valid') try: service = build('drive', 'v3', credentials=creds) # 0. About the user results = service.about().get(fields="*").execute() emailAddress = results['user']['emailAddress'] print(emailAddress) # 1. Call the Drive v3 API results = service.files().list( pageSize=10, fields="nextPageToken, files(id, name)").execute() items = results.get('files', []) if not items: print('No files found.') return print('Files:') for item in items: print(u'{0} ({1})'.format(item['name'], item['id'])) except HttpError as error: # TODO(developer) - Handle errors from drive API. print(f'An error occurred: {error}') if __name__ == '__main__': main() 6 dan from __future__ import print_function import os.path from google.auth.transport.requests import Request from google.oauth2.credentials import Credentials from google_auth_oauthlib.flow import InstalledAppFlow from googleapiclient.discovery import build from googleapiclient.errors import HttpError from googleapiclient.http import MediaFileUpload # If modifying these scopes, delete the file token.json. SCOPES = ['//www.googleapis.com/auth/drive'] def main(): """Shows basic usage of the Drive v3 API. Prints the names and ids of the first 10 files the user has access to. """ token_file = 'gd-token.json' creds = None # The file token.json stores the user's access and refresh tokens, and is # created automatically when the authorization flow completes for the first # time. if os.path.exists(token_file): creds = Credentials.from_authorized_user_file(token_file, SCOPES) # If there are no (valid) credentials available, let the user log in. if not creds or not creds.valid: if creds and creds.expired and creds.refresh_token: print('Requesting new token') creds.refresh(Request()) else: print('First run through so putting up login dialog') # credentials.json downloaded from //console.cloud.google.com/apis/credentials flow = InstalledAppFlow.from_client_secrets_file( 'credentials.json', SCOPES) creds = flow.run_local_server(port=0) # Save the credentials for the next run with open(token_file, 'w') as token: print('Saving new token') print('') token.write(creds.to_json()) else: print('Token valid') try: service = build('drive', 'v3', credentials=creds) # 0. About the user results = service.about().get(fields="*").execute() emailAddress = results['user']['emailAddress'] print(emailAddress) # 1. Call the Drive v3 API results = service.files().list( pageSize=10, fields="nextPageToken, files(id, name)").execute() items = results.get('files', []) if not items: print('No files found.') return print('Files:') for item in items: print(u'{0} ({1})'.format(item['name'], item['id'])) except HttpError as error: # TODO(developer) - Handle errors from drive API. print(f'An error occurred: {error}') if __name__ == '__main__': main() 7
Ada kedaluwarsa yang 1 jam, tapi ini bukan kedaluwarsa refresh_token
Pertama kali masuk sebagai greenbranflakes@gmail. com saya dapat (saya masuk dengan beberapa akun gmail jadi harus memilih)
kemudian
Perhatikan ruang lingkup yang telah kami berikan melalui kode
from __future__ import print_function import os.path from google.auth.transport.requests import Request from google.oauth2.credentials import Credentials from google_auth_oauthlib.flow import InstalledAppFlow from googleapiclient.discovery import build from googleapiclient.errors import HttpError from googleapiclient.http import MediaFileUpload # If modifying these scopes, delete the file token.json. SCOPES = ['//www.googleapis.com/auth/drive'] def main(): """Shows basic usage of the Drive v3 API. Prints the names and ids of the first 10 files the user has access to. """ token_file = 'gd-token.json' creds = None # The file token.json stores the user's access and refresh tokens, and is # created automatically when the authorization flow completes for the first # time. if os.path.exists(token_file): creds = Credentials.from_authorized_user_file(token_file, SCOPES) # If there are no (valid) credentials available, let the user log in. if not creds or not creds.valid: if creds and creds.expired and creds.refresh_token: print('Requesting new token') creds.refresh(Request()) else: print('First run through so putting up login dialog') # credentials.json downloaded from //console.cloud.google.com/apis/credentials flow = InstalledAppFlow.from_client_secrets_file( 'credentials.json', SCOPES) creds = flow.run_local_server(port=0) # Save the credentials for the next run with open(token_file, 'w') as token: print('Saving new token') print('') token.write(creds.to_json()) else: print('Token valid') try: service = build('drive', 'v3', credentials=creds) # 0. About the user results = service.about().get(fields="*").execute() emailAddress = results['user']['emailAddress'] print(emailAddress) # 1. Call the Drive v3 API results = service.files().list( pageSize=10, fields="nextPageToken, files(id, name)").execute() items = results.get('files', []) if not items: print('No files found.') return print('Files:') for item in items: print(u'{0} ({1})'.format(item['name'], item['id'])) except HttpError as error: # TODO(developer) - Handle errors from drive API. print(f'An error occurred: {error}') if __name__ == '__main__': main() _
Berhasil, aplikasi menampilkan file di greenbranflakes@gmail. com drive
Berjalan lagi dan kami tidak diminta untuk masuk lagi karena from __future__ import print_function import os.path from google.auth.transport.requests import Request from google.oauth2.credentials import Credentials from google_auth_oauthlib.flow import InstalledAppFlow from googleapiclient.discovery import build from googleapiclient.errors import HttpError from googleapiclient.http import MediaFileUpload # If modifying these scopes, delete the file token.json. SCOPES = ['//www.googleapis.com/auth/drive'] def main(): """Shows basic usage of the Drive v3 API. Prints the names and ids of the first 10 files the user has access to. """ token_file = 'gd-token.json' creds = None # The file token.json stores the user's access and refresh tokens, and is # created automatically when the authorization flow completes for the first # time. if os.path.exists(token_file): creds = Credentials.from_authorized_user_file(token_file, SCOPES) # If there are no (valid) credentials available, let the user log in. if not creds or not creds.valid: if creds and creds.expired and creds.refresh_token: print('Requesting new token') creds.refresh(Request()) else: print('First run through so putting up login dialog') # credentials.json downloaded from //console.cloud.google.com/apis/credentials flow = InstalledAppFlow.from_client_secrets_file( 'credentials.json', SCOPES) creds = flow.run_local_server(port=0) # Save the credentials for the next run with open(token_file, 'w') as token: print('Saving new token') print('') token.write(creds.to_json()) else: print('Token valid') try: service = build('drive', 'v3', credentials=creds) # 0. About the user results = service.about().get(fields="*").execute() emailAddress = results['user']['emailAddress'] print(emailAddress) # 1. Call the Drive v3 API results = service.files().list( pageSize=10, fields="nextPageToken, files(id, name)").execute() items = results.get('files', []) if not items: print('No files found.') return print('Files:') for item in items: print(u'{0} ({1})'.format(item['name'], item['id'])) except HttpError as error: # TODO(developer) - Handle errors from drive API. print(f'An error occurred: {error}') if __name__ == '__main__': main() 3 disimpan di sistem file
Token
Saya memiliki tugas cron yang berjalan setiap menit di server yang mungkin perlu mengunggah file menggunakan metode di atas
Setelah masuk, dan token disalin ke server, bagaimana saya bisa menangani from __future__ import print_function import os.path from google.auth.transport.requests import Request from google.oauth2.credentials import Credentials from google_auth_oauthlib.flow import InstalledAppFlow from googleapiclient.discovery import build from googleapiclient.errors import HttpError from googleapiclient.http import MediaFileUpload # If modifying these scopes, delete the file token.json. SCOPES = ['//www.googleapis.com/auth/drive'] def main(): """Shows basic usage of the Drive v3 API. Prints the names and ids of the first 10 files the user has access to. """ token_file = 'gd-token.json' creds = None # The file token.json stores the user's access and refresh tokens, and is # created automatically when the authorization flow completes for the first # time. if os.path.exists(token_file): creds = Credentials.from_authorized_user_file(token_file, SCOPES) # If there are no (valid) credentials available, let the user log in. if not creds or not creds.valid: if creds and creds.expired and creds.refresh_token: print('Requesting new token') creds.refresh(Request()) else: print('First run through so putting up login dialog') # credentials.json downloaded from //console.cloud.google.com/apis/credentials flow = InstalledAppFlow.from_client_secrets_file( 'credentials.json', SCOPES) creds = flow.run_local_server(port=0) # Save the credentials for the next run with open(token_file, 'w') as token: print('Saving new token') print('') token.write(creds.to_json()) else: print('Token valid') try: service = build('drive', 'v3', credentials=creds) # 0. About the user results = service.about().get(fields="*").execute() emailAddress = results['user']['emailAddress'] print(emailAddress) # 1. Call the Drive v3 API results = service.files().list( pageSize=10, fields="nextPageToken, files(id, name)").execute() items = results.get('files', []) if not items: print('No files found.') return print('Files:') for item in items: print(u'{0} ({1})'.format(item['name'], item['id'])) except HttpError as error: # TODO(developer) - Handle errors from drive API. print(f'An error occurred: {error}') if __name__ == '__main__': main() 5 yang saya yakin akan kedaluwarsa setelah 1 minggu. Ya benar -
Token telah kedaluwarsa atau dicabut
- pembicaraan bagus di komentar tentang token penyegaran. Strategi di sini melakukan apa yang dilakukan API Python dan menghasilkan refresh_token jadi saya yakin kita tidak perlu menggunakan ini?
Sepertinya hanya dapat 1 minggu from __future__ import print_function import os.path from google.auth.transport.requests import Request from google.oauth2.credentials import Credentials from google_auth_oauthlib.flow import InstalledAppFlow from googleapiclient.discovery import build from googleapiclient.errors import HttpError from googleapiclient.http import MediaFileUpload # If modifying these scopes, delete the file token.json. SCOPES = ['//www.googleapis.com/auth/drive'] def main(): """Shows basic usage of the Drive v3 API. Prints the names and ids of the first 10 files the user has access to. """ token_file = 'gd-token.json' creds = None # The file token.json stores the user's access and refresh tokens, and is # created automatically when the authorization flow completes for the first # time. if os.path.exists(token_file): creds = Credentials.from_authorized_user_file(token_file, SCOPES) # If there are no (valid) credentials available, let the user log in. if not creds or not creds.valid: if creds and creds.expired and creds.refresh_token: print('Requesting new token') creds.refresh(Request()) else: print('First run through so putting up login dialog') # credentials.json downloaded from //console.cloud.google.com/apis/credentials flow = InstalledAppFlow.from_client_secrets_file( 'credentials.json', SCOPES) creds = flow.run_local_server(port=0) # Save the credentials for the next run with open(token_file, 'w') as token: print('Saving new token') print('') token.write(creds.to_json()) else: print('Token valid') try: service = build('drive', 'v3', credentials=creds) # 0. About the user results = service.about().get(fields="*").execute() emailAddress = results['user']['emailAddress'] print(emailAddress) # 1. Call the Drive v3 API results = service.files().list( pageSize=10, fields="nextPageToken, files(id, name)").execute() items = results.get('files', []) if not items: print('No files found.') return print('Files:') for item in items: print(u'{0} ({1})'.format(item['name'], item['id'])) except HttpError as error: # TODO(developer) - Handle errors from drive API. print(f'An error occurred: {error}') if __name__ == '__main__': main() _5 dengan cara ini untuk 'menguji' aplikasi sebelum harus melalui proses persetujuan lagi
https. //stackoverflow. com/questions/66058279/token-has-been-expired-or-revoked-google-oauth2-refresh-token-gets-expired-i?noredirect=1&lq=1
- Gunakan akun Google Workspace berbayar (bukan gmail standar) dan buat layar persetujuan OAuth, Jenis Pengguna. { "installed": { "client_id": "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx.apps.googleusercontent.com", "project_id": "auto-archiver-1111111", "auth_uri": "//accounts.google.com/o/oauth2/auth", "token_uri": "//oauth2.googleapis.com/token", "auth_provider_x509_cert_url": "//www.googleapis.com/oauth2/v1/certs", "client_secret": "xxxxxxx-xxxxxxxxxxxxxxxxxxxxxx-xxxxxxxxxxx", "redirect_uris": [ "//localhost" ] } } 1. lihat semua di bawah ini
- Status Penerbitan. Mulai dari Pengujian hingga Dipublikasikan - tetapi Google harus menyetujuinya?… lihat semuanya di bawah
client_secret.json diunduh dari konsol. awan. google. com
{ "installed": { "client_id": "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx.apps.googleusercontent.com", "project_id": "auto-archiver-1111111", "auth_uri": "//accounts.google.com/o/oauth2/auth", "token_uri": "//oauth2.googleapis.com/token", "auth_provider_x509_cert_url": "//www.googleapis.com/oauth2/v1/certs", "client_secret": "xxxxxxx-xxxxxxxxxxxxxxxxxxxxxx-xxxxxxxxxxx", "redirect_uris": [ "//localhost" ] } }
Berikut adalah contoh from __future__ import print_function import os.path from google.auth.transport.requests import Request from google.oauth2.credentials import Credentials from google_auth_oauthlib.flow import InstalledAppFlow from googleapiclient.discovery import build from googleapiclient.errors import HttpError from googleapiclient.http import MediaFileUpload # If modifying these scopes, delete the file token.json. SCOPES = ['//www.googleapis.com/auth/drive'] def main(): """Shows basic usage of the Drive v3 API. Prints the names and ids of the first 10 files the user has access to. """ token_file = 'gd-token.json' creds = None # The file token.json stores the user's access and refresh tokens, and is # created automatically when the authorization flow completes for the first # time. if os.path.exists(token_file): creds = Credentials.from_authorized_user_file(token_file, SCOPES) # If there are no (valid) credentials available, let the user log in. if not creds or not creds.valid: if creds and creds.expired and creds.refresh_token: print('Requesting new token') creds.refresh(Request()) else: print('First run through so putting up login dialog') # credentials.json downloaded from //console.cloud.google.com/apis/credentials flow = InstalledAppFlow.from_client_secrets_file( 'credentials.json', SCOPES) creds = flow.run_local_server(port=0) # Save the credentials for the next run with open(token_file, 'w') as token: print('Saving new token') print('') token.write(creds.to_json()) else: print('Token valid') try: service = build('drive', 'v3', credentials=creds) # 0. About the user results = service.about().get(fields="*").execute() emailAddress = results['user']['emailAddress'] print(emailAddress) # 1. Call the Drive v3 API results = service.files().list( pageSize=10, fields="nextPageToken, files(id, name)").execute() items = results.get('files', []) if not items: print('No files found.') return print('Files:') for item in items: print(u'{0} ({1})'.format(item['name'], item['id'])) except HttpError as error: # TODO(developer) - Handle errors from drive API. print(f'An error occurred: {error}') if __name__ == '__main__': main() _3 yang dihasilkan setelah dijalankan melalui proses di https. // pengembang. google. com/drive/api/quickstart/python
{ "token": "ya29.xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx", // refreshed every hour "refresh_token": "1//xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx", // stays the same "token_uri": "//oauth2.googleapis.com/token", "client_id": "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxx.apps.googleusercontent.com", // OAuth Client ID from console.cloud.google.com (from client_secret.json) "client_secret": "xxxxxxx-xxxxxxxxxxxxxxxxxxxxxxxx-xxxxxxxxxxx", // OAuth Client secret from console.cloud.google.com (from client_secret.json) "scopes": [ "//www.googleapis.com/auth/drive" ], "expiry": "2022-06-30T10:11:19.033586Z" // Zulu or GMT time. -1 hour in British Summer time. When the token expires (every hour) }
Unggah file ke Drive milik sendiri
Sebagai pengguna greenbranflakes@gmail. com
# Change scope to give full access to the Drive SCOPES = ['//www.googleapis.com/auth/drive'] # service account # creds = Credentials.from_service_account_file('service_account.json', scopes=SCOPES) # oauth - assume the refresh token is there creds = Credentials.from_authorized_user_file('token.json', SCOPES) # .. snip . see above # 2. Upload a file to a folder gbf_folder = '1WQf421zvXKJpWEeEY1YV9seEwgMCdxlZ' file_metadata = { 'name': 'photo.jpg', 'parents': [gbf_folder] } media = MediaFileUpload('files/photo.jpg', mimetype='image/jpeg', resumable=True) file = service.files().create(body=file_metadata, media_body=media, fields='id').execute()
https. //github. com/djhmateer/auto-archiver/blob/main/dm_drive3_upload. py memiliki contoh yang bagus tentang cara melakukan tindakan yang berbeda
3. OAuth2 dengan Pengguna Google Workspace (berbayar)
https. // ruang kerja. google. com/intl/en_uk/pricing. html ini memberikan penyimpanan cloud 30GB, dan email khusus. Ini yang saya gunakan untuk perusahaan saya khusus untuk email. dave@hmsoftware. bersama. inggris
Workspace dapat membeli penyimpanan dari One di bawah
https. //satu. google. com/storage Ini adalah Google One tempat davemateeer@gmail saya. email com mendapatkan penyimpanan 100GB (saya menggunakannya untuk menyimpan semua foto dan cadangan saya dari iPhone) dengan harga £1. 59 per bulan
https. //menghibur. awan. google. com/ mari buat proyek dan aktifkan API untuk dave@hmsoftware. bersama. inggris
https. // pengembang. google. com/drive/api/quickstart/python quickstart Drive API ini adalah tempat yang bagus
- Buat proyek baru - Auto Archiver HMS
- Memungkinkan. API Google Drive
Layar persetujuan OAuth, Jenis Pengguna. Intern
Kredensial, Buat OAuth
client_secret.json atau from __future__ import print_function import os.path from google.auth.transport.requests import Request from google.oauth2.credentials import Credentials from google_auth_oauthlib.flow import InstalledAppFlow from googleapiclient.discovery import build from googleapiclient.errors import HttpError from googleapiclient.http import MediaFileUpload # If modifying these scopes, delete the file token.json. SCOPES = ['//www.googleapis.com/auth/drive'] def main(): """Shows basic usage of the Drive v3 API. Prints the names and ids of the first 10 files the user has access to. """ token_file = 'gd-token.json' creds = None # The file token.json stores the user's access and refresh tokens, and is # created automatically when the authorization flow completes for the first # time. if os.path.exists(token_file): creds = Credentials.from_authorized_user_file(token_file, SCOPES) # If there are no (valid) credentials available, let the user log in. if not creds or not creds.valid: if creds and creds.expired and creds.refresh_token: print('Requesting new token') creds.refresh(Request()) else: print('First run through so putting up login dialog') # credentials.json downloaded from //console.cloud.google.com/apis/credentials flow = InstalledAppFlow.from_client_secrets_file( 'credentials.json', SCOPES) creds = flow.run_local_server(port=0) # Save the credentials for the next run with open(token_file, 'w') as token: print('Saving new token') print('') token.write(creds.to_json()) else: print('Token valid') try: service = build('drive', 'v3', credentials=creds) # 0. About the user results = service.about().get(fields="*").execute() emailAddress = results['user']['emailAddress'] print(emailAddress) # 1. Call the Drive v3 API results = service.files().list( pageSize=10, fields="nextPageToken, files(id, name)").execute() items = results.get('files', []) if not items: print('No files found.') return print('Files:') for item in items: print(u'{0} ({1})'.format(item['name'], item['id'])) except HttpError as error: # TODO(developer) - Handle errors from drive API. print(f'An error occurred: {error}') if __name__ == '__main__': main() 0 yang merupakan kode Python menyebutnya
Ini berfungsi sekarang - saya menggunakan akun layanan lama untuk berbicara dengan spreadsheet, dan akun OAuth Google Workspace baru untuk berbicara dengan Drive
Tapi siapa yang tahu berapa lama from __future__ import print_function import os.path from google.auth.transport.requests import Request from google.oauth2.credentials import Credentials from google_auth_oauthlib.flow import InstalledAppFlow from googleapiclient.discovery import build from googleapiclient.errors import HttpError from googleapiclient.http import MediaFileUpload # If modifying these scopes, delete the file token.json. SCOPES = ['//www.googleapis.com/auth/drive'] def main(): """Shows basic usage of the Drive v3 API. Prints the names and ids of the first 10 files the user has access to. """ token_file = 'gd-token.json' creds = None # The file token.json stores the user's access and refresh tokens, and is # created automatically when the authorization flow completes for the first # time. if os.path.exists(token_file): creds = Credentials.from_authorized_user_file(token_file, SCOPES) # If there are no (valid) credentials available, let the user log in. if not creds or not creds.valid: if creds and creds.expired and creds.refresh_token: print('Requesting new token') creds.refresh(Request()) else: print('First run through so putting up login dialog') # credentials.json downloaded from //console.cloud.google.com/apis/credentials flow = InstalledAppFlow.from_client_secrets_file( 'credentials.json', SCOPES) creds = flow.run_local_server(port=0) # Save the credentials for the next run with open(token_file, 'w') as token: print('Saving new token') print('') token.write(creds.to_json()) else: print('Token valid') try: service = build('drive', 'v3', credentials=creds) # 0. About the user results = service.about().get(fields="*").execute() emailAddress = results['user']['emailAddress'] print(emailAddress) # 1. Call the Drive v3 API results = service.files().list( pageSize=10, fields="nextPageToken, files(id, name)").execute() items = results.get('files', []) if not items: print('No files found.') return print('Files:') for item in items: print(u'{0} ({1})'.format(item['name'], item['id'])) except HttpError as error: # TODO(developer) - Handle errors from drive API. print(f'An error occurred: {error}') if __name__ == '__main__': main() _5 di from __future__ import print_function import os.path from google.auth.transport.requests import Request from google.oauth2.credentials import Credentials from google_auth_oauthlib.flow import InstalledAppFlow from googleapiclient.discovery import build from googleapiclient.errors import HttpError from googleapiclient.http import MediaFileUpload # If modifying these scopes, delete the file token.json. SCOPES = ['//www.googleapis.com/auth/drive'] def main(): """Shows basic usage of the Drive v3 API. Prints the names and ids of the first 10 files the user has access to. """ token_file = 'gd-token.json' creds = None # The file token.json stores the user's access and refresh tokens, and is # created automatically when the authorization flow completes for the first # time. if os.path.exists(token_file): creds = Credentials.from_authorized_user_file(token_file, SCOPES) # If there are no (valid) credentials available, let the user log in. if not creds or not creds.valid: if creds and creds.expired and creds.refresh_token: print('Requesting new token') creds.refresh(Request()) else: print('First run through so putting up login dialog') # credentials.json downloaded from //console.cloud.google.com/apis/credentials flow = InstalledAppFlow.from_client_secrets_file( 'credentials.json', SCOPES) creds = flow.run_local_server(port=0) # Save the credentials for the next run with open(token_file, 'w') as token: print('Saving new token') print('') token.write(creds.to_json()) else: print('Token valid') try: service = build('drive', 'v3', credentials=creds) # 0. About the user results = service.about().get(fields="*").execute() emailAddress = results['user']['emailAddress'] print(emailAddress) # 1. Call the Drive v3 API results = service.files().list( pageSize=10, fields="nextPageToken, files(id, name)").execute() items = results.get('files', []) if not items: print('No files found.') return print('Files:') for item in items: print(u'{0} ({1})'.format(item['name'], item['id'])) except HttpError as error: # TODO(developer) - Handle errors from drive API. print(f'An error occurred: {error}') if __name__ == '__main__': main() 3 akan bekerja? . //stackoverflow. com/questions/66058279/token-has-been-expired-or-revoked-google-oauth2-refresh-token-gets-expired-i?noredirect=1&lq=1 kesimpulannya adalah bahwa Pengujian Eksternal dan diterbitkan, memiliki 7 hari. Dan tidak disebutkan tentang token Internal
Jenis Pengguna Internal/Eksternal dan Status Penerbitan Pengujian / Dalam produksi
4. OAuth dengan Publish Status Published dan External non Workspace User
kemudian
Sehat. ini akan bekerja setelah 1 minggu?
Ini terlihat menjanjikan. Saya tidak keberatan dengan peringatan dari Google karena saya satu-satunya orang yang menggunakan layanan ini
5
Lampiran
kunci API
https. // pengembang. google. com/drive/api/v3/reference/about/get About. Dapatkan
Saya membuat kunci API namun tidak dapat mengotorisasinya
curl \ '//www.googleapis.com/drive/v3/about?key=[YOUR_API_KEY]' \ --header 'Authorization: Bearer [YOUR_ACCESS_TOKEN]' \ --header 'Accept: application/json' \ --compressed
Terutama karena saya tidak bisa mendapatkan token akses (saya tidak menggunakan OAuth2)
Akun Layanan
Kode
https. // pengembang. google. com/drive/api/quickstart/python Google Drive untuk Pengembang Drive API - Python
https. // pengembang. google. com/drive/api/guides/manage-uploads
Mencetak nama file dan ID dari semua yang dibagikan dengan akun layanan ini. Ini menghasilkan daftar datar sehingga file dalam subdirektori akan dicantumkan
https. //github. com/googleworkspace/python-samples/blob/master/drive/quickstart/quickstart. py Sampel
Mengunggah file
https. //github. com/iterative/PyDrive2 - dapat menggunakan ini
https. // pengembang. google. com/drive/api/guides/search-files API docs
https. //github. com/googleworkspace/python-samples/tree/master/drive/driveapp
Lampiran - Konsol Google
https. //menghibur. awan. google. com/ - tempat Anda mengizinkan akses
https. // admin. google. com/ hanya digunakan untuk akun Google Workspace
Lampiran - Desktop Google Drive
Menggunakan Google Drive Desktop, Anda dapat melihat semua file Anda sebagai drive tertaut { "installed": { "client_id": "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx.apps.googleusercontent.com", "project_id": "auto-archiver-1111111", "auth_uri": "//accounts.google.com/o/oauth2/auth", "token_uri": "//oauth2.googleapis.com/token", "auth_provider_x509_cert_url": "//www.googleapis.com/oauth2/v1/certs", "client_secret": "xxxxxxx-xxxxxxxxxxxxxxxxxxxxxx-xxxxxxxxxxx", "redirect_uris": [ "//localhost" ] } } 8 di Windows Explorer