안녕하세요. 프즈입니다.
구글 드라이브 연동해서 파일 목록 읽고 업로드해봤어요
특정 파일이 주기적으로 생기면 구글 드라이브에 올리도록 하는 크론을 만들고 싶었는데요
튜토리얼 따라 했던 후기 공유해요
구글에서 일단 google drive quict start guide라고 검색해서 나오는 문서를 보고 했어요
오타 났는데도 잘 나오네요
지금은 잘 나왔는데 나중에 바뀔 수도 있으니 주소를 메모합니다
가이드 문서 - https://developers.google.com/drive/api/v3/quickstart/python
Enable the Drive API 클릭하세요
그럼 구글 드라이브를 연동하는 프로젝트를 생성하는 화면이 나와요
여기서 정하는 이름이 나중에 구글 드라이브를 연동할 때 확인 가능한 이름입니다
저는 처음 테스트해보는 것이어서 그냥 Quickstart로 했어요
다음 클라이언트 형태를 선택하는 화면에서 TVs and Limited Input devices라고 선택했어요
그냥 콘솔 프로그램을 테스트하는데 그나마 가까운 게 이거 같더라고요
그럼 파일을 다운로드할 수 있는 버튼을 눌러서 다운로드하면 credentials.json이런 이름으로 받아져요
이 파일을 만들고 있는 프로젝트에 복사합니다
구글 드라이브 사용에 필요한 것들을 pip로 설치합니다
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
# If modifying these scopes, delete the file token.pickle.
SCOPES = ['https://www.googleapis.com/auth/drive.metadata.readonly']
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.
"""
creds = None
# The file token.pickle 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.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(
'credentials.json', 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)
service = build('drive', 'v3', credentials=creds)
# 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.')
else:
print('Files:')
for item in items:
print(u'{0} ({1})'.format(item['name'], item['id']))
if __name__ == '__main__':
main()
기본 코드에서 SCOPE 부분이 일기 전용인데요
업로드도 하려면 수정해야 합니다
SCOPES = ['https://www.googleapis.com/auth/drive.metadata.readonly']
윗부분을 찾아서 아래처럼 수정하면 업로드도 가능합니다
.metadata.readonly 이 부분을 지웠어요
SCOPES = ['https://www.googleapis.com/auth/drive']
이제 코드를 실행해보면 구글 로그인 화면이 나오는데요
최초 한 번만 로그인하고 접근 허용하면 token.pickle 파일이 생겨요
그럼 그 이후에는 로그인하지 않아도 알아서 생긴 토큰 파일을 이용해서 접근합니다
실행하면 구글 드라이브 목록이 나오는데요. 업로드도 해보겠습니다
업로드하는 샘플 코드를 구하기 위해 구글에 검색해봤어요
첫 번째 결과를 클릭하면 샘플 업로드 코드를 구할 수 있어요
file_metadata = {'name': 'photo.jpg'}
media = MediaFileUpload('files/photo.jpg', mimetype='image/jpeg')
service = build('drive', 'v3', credentials=creds)
file = drive_service.files().create(body=file_metadata,
media_body=media,
fields='id').execute()
print('File ID: {}'.format(file.get('id')))
샘플 코드에서 print 부분을 python3 버전에 맞게 수정하고 service 라인을 추가했어요
마지막으로 위에 import를 추가하고 실행하면 파일 업로드가 잘 됩니다~
from apiclient.http import MediaFileUpload
처음에는 좀 복잡하게 느껴졌었는데 해보니까 할만하네요
할만하다고 했지만 한참 지나서 하려면 생각나지 않을 것을 알아 이렇게 메모합니다
'코딩 프로그래밍 > PYTHON 파이썬' 카테고리의 다른 글
Python Flask Gunicorn Timeout 시간 초과 늘이기 (0) | 2020.10.15 |
---|---|
Python Flask 캐시 기능 끄기 (0) | 2020.10.12 |
Python Flask http 를 https 로 연결하는 방법 (0) | 2020.10.11 |
파이썬 Flask 에서 url 주소 파라미터 검사 방법 (0) | 2020.10.11 |
Python 크롤링 할때 단축키 전송하기 (1) | 2020.10.10 |
댓글