티스토리 뷰
<Functions>
- Upload files
- Download files
- Write spreadsheets
<Preparations>
- Google APIs > User Authentication > ... >사용자 인증정보 만들기 > OAuth Client ID > 'Create(생성)'
- "pip install --upgrade google-api-python-client google-auth-httplib2 google-auth-oauthlib"
from __future__ import print_function
import pickle
import os.path
from googleapiclient.discovery import build
from google_auth_oauthlib.flow import InstalledAppFlow
from google.auth.transport.requests import Request
from apiclient.http import MediaFileUpload, MediaIoBaseDownload
import os, io
import gspread
class cGoogleDrive:
SCOPES = [
'https://www.googleapis.com/auth/drive',
'https://spreadsheets.google.com/feeds'
]
CLIENT_SCERET_FILE = 'client_secret_....json'
APPLICATIONNAME = '[I2B] Google Drive API Test'
def __init__(self):
creds = None
# created automatically when the authorization flow completes for the first
# time.
if os.path.exists('token.pickle'):
with open('token.pickle', 'rb') as token:
creds = pickle.load(token)
# 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:
creds.refresh(Request())
else:
flow = InstalledAppFlow.from_client_secrets_file(
CLIENT_SCERET_FILE, SCOPES)
creds = flow.run_local_server(port=0)
# Save the credentials for the next run
with open('token.pickle', 'wb') as token:
pickle.dump(creds, token)
self.DriveCredentials = creds
self.DriveService = build('drive', 'v3', credentials=creds)
def ListFiles(self, size):
results = self.DriveService.files().list(
pageSize=size, fields="nextPageToken, files(id, name)").execute()
items = results.get('files', [])
if not items:
print('No files found.')
else:
print('Files:')
for item in items:
print(u'{0} ({1})'.format(item['name'], item['id']))
def UploadFile(self, filename, filepath, mimetype):
file_metadata = {'name':filename}
media = MediaFileUpload(filepath, mimetype=mimetype)
file = self.DriveService.files().create(body=file_metadata, media_body=media, fields='id').execute()
print('file ID: %s' %file.get('id'))
def DownloadFile(self, file_id, filepath):
request = self.DriveService.files().get_media(fileId=file_id)
fh = io.BytesIO()
downloader = MediaIoBaseDownload(fh, request)
done = False
while done is False:
status, done = downloader.next_chunk()
print("Download %d%%." %int(status.progress()*100))
with io.open(filepath, 'wb') as f:
fh.seek(0)
f.write(fh.read())
def CreateFolder(self, name):
file_metadata = {
'name':name,
'mimeType': 'application/vnd.google-apps.folder'
}
file = self.DriveService.files().create(body=file_metadata, fields='id').execute()
print('Folder ID: %s' %file.get('id'))
def SearchFiles(self, size, query):
results = self.DriveService.files().list(
pageSize=size, fields="nextPageToken, files(id, name)", q=query).execute()
items = results.get('files', [])
if not items:
print('No files found.')
else:
print('Files:')
for item in items:
print(u'{0} ({1})'.format(item['name'], item['id']))
def GetSpreadSheet(self, fileName):
gc = gspread.authorize(self.DriveCredentials)
gs = gc.create(fileName)
return gs
def WriteSpread(self, googleSpread, sheetName, cellInfos):
worksheet = googleSpread.add_worksheet(title=sheetName, rows='100', cols='10')
rowNo =1
count11 = 0
for cellInfo1 in cellInfos:
linkAddress1 = cellInfo1['address']
linkTitle1 = cellInfo1['title']
linkBody1 = cellInfo1['body']
overlapped1 = False
count21 = 0
for cellInfo2 in cellInfos:
if(count21 >= count11):
break
if linkAddress1 == cellInfo2['address']:
overlapped1 = True
break
count21 += 1
if not overlapped1:
worksheet.update_acell("B"+str(rowNo), linkAddress1)
worksheet.update_acell("C"+str(rowNo), linkTitle1)
worksheet.update_acell("D"+str(rowNo), linkBody1)
rowNo += 1
count11 += 1
# Sorry, you have exceeded your sharing quota
# --> Logout and re-login
def TransferSheet(self, googleSpread):
googleSpread.share('bilient2014@gmail.com', perm_type='user', role='owner')
def UploadXLSXFiles(self):
반응형
'SWDesk > App' 카테고리의 다른 글
지상 기상 데이터 수집 프로그램 소스 (0) | 2021.03.29 |
---|---|
해상 기상 데이터 수집 프로그램 소스 (0) | 2021.03.22 |
JSON 배열 전송 및 수신 : Python to PHP (2) | 2021.01.13 |
[Python] Example for Naver Search with Naver-API (0) | 2021.01.08 |
[Python] Example for Naver Search with selenium (0) | 2021.01.05 |
반응형
250x250
최근에 올라온 글
최근에 달린 댓글
- Total
- Today
- Yesterday
링크
TAG
- Decorator
- Video
- 혁신
- 치매
- 둎
- 배프
- 티스토리챌린지
- DYOV
- 전류
- Innovation&Hurdles
- Innovations
- 전압
- Hurdles
- 심심풀이치매방지기
- Innovations&Hurdles
- bilient
- 빌리언트
- 전압전류모니터링
- ServantClock
- arduino
- 허들
- 치매방지
- 절연형
- 심심풀이
- 혁신과허들
- 오블완
- image
- BSC
- badp
- 아두이노
일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
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 |
글 보관함