리그캣의 개발놀이터

구글 드라이브 api 연동하기 본문

팀 활동/인턴쉽

구글 드라이브 api 연동하기

리그캣 2018. 1. 23. 15:34

구글 api 연동하기


방향


1.        먼저 중요한 구글 드라이브 api 보고서 문서에 접근할 있는지 알아 보고(이때 아마 특정 아이디 비밀번호? 토큰을 알아서 넣어야 할듯..)


2.        문서 접근이 성공했으면 안에 있는 내용을 빼올 있나 알아보자.


3.        다음은 크롤링을 하든 안에 특정 내용을 빼내는 방법을 알아봐야 할거야.


구글 api 사용하기


https://console.cloud.google.com/ 접속 동의 api 프로젝트 생성 시키기.


Google Developer Console 계정으로 구글API(G suite API)선택하기


사용자 인증정보 만들기 클릭 API OAuth 클라이언트 ID 발급 받기.



파이썬을 이용한 구글 드라이브 API

https://developers.google.com/drive/v3/web/quickstart/python

참고하기.

 

구글 api 라이브러리 다운로드

https://pypi.python.org/pypi/google-api-python-client/

윈도우 환경에서 eazy_install, pip 사용하기

http://be4rpooh02.tistory.com/8

 

pip 실행을 위해 환경변수 path 설정해주기 http://ssse.tistory.com/36




cmd 창에서 pip명령어 입력해서 라이브러리 설치하기.



Python internbot 프로젝트 생성해서, 디렉토리(quickstart.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
66
67
68
69
70
71
72
73
from __future__ import print_function
import httplib2
import os
 
from apiclient import discovery
from oauth2client import client
from oauth2client import tools
from oauth2client.file import Storage
 
try:
    import argparse
    flags = argparse.ArgumentParser(parents=[tools.argparser]).parse_args()
except ImportError:
    flags = None
 
# If modifying these scopes, delete your previously saved credentials
# at ~/.credentials/drive-python-quickstart.json
SCOPES = 'https://www.googleapis.com/auth/drive.metadata.readonly'
CLIENT_SECRET_FILE = 'client_secret.json' //자신의 OAuth 2.0 클라이언트 ID 파일 이름.
APPLICATION_NAME = 'Drive API Python Quickstart'
 
 
def get_credentials():
    """Gets valid user credentials from storage.
    If nothing has been stored, or if the stored credentials are invalid,
    the OAuth2 flow is completed to obtain the new credentials.
    Returns:
        Credentials, the obtained credential.
    """
    home_dir = os.path.expanduser('~')
    credential_dir = os.path.join(home_dir, '.credentials')
    if not os.path.exists(credential_dir):
        os.makedirs(credential_dir)
    credential_path = os.path.join(credential_dir,
                                   'drive-python-quickstart.json')
 
    store = Storage(credential_path)
    credentials = store.get()
    if not credentials or credentials.invalid:
        flow = client.flow_from_clientsecrets(CLIENT_SECRET_FILE, SCOPES)
        flow.user_agent = APPLICATION_NAME
        if flags:
            credentials = tools.run_flow(flow, store, flags)
        else# Needed only for compatibility with Python 2.6
            credentials = tools.run(flow, store)
        print('Storing credentials to ' + credential_path)
    return credentials
 
def main():
    """Shows basic usage of the Google Drive API.
    Creates a Google Drive API service object and outputs the names and IDs
    for up to 10 files.
    """
    credentials = get_credentials()
    http = credentials.authorize(httplib2.Http())
    service = discovery.build('drive''v3', http=http)
 
    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('{0} ({1})'.format(item['name'], item['id']))
 
if __name__ == '__main__':
    main()
 
cs



OAuth 2.0 클라이언트 ID JSON폴더를 앞에서 생성한 Python 프로젝트에 넣기


quickstart.py 파일 RUN 한후 실행 창의 링크로 들어가 계정에 액세스하도록 허용하기.

'팀 활동 > 인턴쉽' 카테고리의 다른 글

인턴 봇 - 최종 발표  (0) 2018.01.23
정규식 활용하기  (0) 2018.01.23
서비스 구현 계획서 - 데일리 봇  (0) 2018.01.23
기획안 - daily bot 데일리봇 (챗봇)  (0) 2018.01.23
Comments