끄적끄적 인턴생활 (2020)

구글 드라이브 API, 폴더 생성과 파일 업로드 (python)

jellylucy 2021. 12. 28. 13:04

 

(1) Step 3: Set up the sample

SCOPE : 토큰 키의 권한 설정을 해준다 .

예시 코드는 읽기전용.

# If modifying these scopes, delete the file token.pickle.
SCOPES = ['https://www.googleapis.com/auth/drive.metadata.readonly']
 
SCOPES = ['https://www.googleapis.com/auth/drive.metadata]
 

SCOPE를 모든권한 허용으로 바꾼 뒤 코드 실행.

 

뜨는 새로운 구글 로그인창에 들어가서

생성된 Quickstart 앱을

Google 드라이브 파일 보기 수정 생성 삭제 란을 허용해준다.

 

그 후, 토큰키를 받는 것.

 

 

*파이썬의 pickle은 변수 정보를 저장하는 역할.

 

creds = None으로 변수 저장을 한 뒤,

토큰이 있으면 저장하고

토큰이 없거나 유효만료되었다면 토큰 재생성 등등의 조건문을 실행한다

#권한 인증 및 토큰 확인 
SCOPES = ['https://www.googleapis.com/auth/drive']
creds = None

#이미 발급받은 토큰이 있을때
if os.path.exists('token.pickle'):
        with open('token.pickle', 'rb') as token:
            creds = pickle.load(token)


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)
 

 


# Save the credentials for the next run

with open('token.pickle', 'wb') as token:

pickle.dump(creds, token)

 

dump()은 pickle을 생성한다는 뜻이다.

만약 이 코드를 실행 후 생성된 token pickle을 삭제하면 다시 생성하라는 창이 뜨게 됨.

 

 

#연결 인스턴스 생성
service = build('drive', 'v3', credentials=creds)
 

*중요 코드

구글 드라이브와 파이썬을 연결시켜주는 파이프 변수.

 

#드라이브 폴더 생성
file_metadata = {
    'name': 'Invoices',
    'mimeType': 'application/vnd.google-apps.folder'
}
#    폴더 실행문
file =service.files().create(body=file_metadata,fields='id').execute()
print ('Folder ID: %s' % file.get('id'))
 

file_metadata 라는 파일 이름, 파일 경로를 가진 곳에

service으로 create해준다( 폴더 생성)

-> file.get으로 생성된 폴더의 id 값을 얻을 수 있는데

이것으로 나중에 이 id값 폴더에 어떤 파일을 upload. 이런식으로 사용하게 됨

 

#파일 업로드
from googleapiclient.http import MediaFileUpload
file_metadata = {'name': 'mkdir.py','parents':['1zvr9O3z90OSmvndbEPsHkVYiRlfmJuNj']}
media = MediaFileUpload('mkdir.py',resumable=True)
#위에 줄은 파일경로
file = service.files().create(body=file_metadata,
                                    media_body=media,
                                    fields='id').execute()
print ('File ID: %s' % file.get('id'))
 

(1)file_metadata

업로드할 파일 이름. 위치 'parents' : ['위에서 생성한 폴더 id']

(2)media

파일 경로.

(3)service으로 create

(4) 생성된 업로드파일 id 생성