메뉴 건너뛰기

infra

[Gdata] API v4 사용 for Python with Auth

lispro062017.10.12 22:59조회 수 495댓글 0

  • 6
    • 글자 크기

인증은 초기 설정 외에 사용할 일이 없어 자주 잊는 부분이라, 이번에 정리해 둔다.


구글에서 제공하는 문서는 죄다 영어로 캡처 없이 되어 있어 자세히 읽고, 메뉴를 잘 찾아가지 않으면 당최 알 수가 없다.


1.JPG

2.JPG

3.JPG


이 부분에서 사용자 인증정보를 다시 클릭하여, 사용자 인증 정보 만들기의 OAuth 클라이언트 ID를 선택한다.


4.JPG

이름은 아무거나 하면 되고, 기타를 선택

5.JPG

만들어진 id에서 사용할 secret 파일을 적당한 이름으로 변경하여 다운로드 한다.(json)

6.JPG


서버에 업로드하여, 경로 설정을 확인하고, 인증할 범위(읽기 전용을 해제하였다.)와 각 경로들을 수정한다. 기존 api의 json 경로가 동일하면 재인증 절차 없이 실행되어 권한 없음 같은 메시지가 나오므로 이름을 바꾸거나 지우고 시도한다.(영어로 범위가 변경되었다면, 저장된 크레덴셜을 지우라고 되어있다.)

아래 소스는 구글 슬라이드 API 의 슬라이드 생성 명령을 통해 제목이 있는 레이아웃의 슬라이드를 생성하는 코드이다. 처음 시작 예제는 get으로 슬라이드와 개체 수를 구하는 것인데, 레퍼런스 문서들을 참조해도 응용하기 어렵다. page_id의 경우 겹치지 않는 임의 id를 지정하면 된다. 별 설명이 없어 기존 id를 넣어봤는데, unique 한 id로 지정해야 한다는 에러를 응답하고, 4자로 하면 5자 이상으로 설정하라고 나온다. API의 예제들이 너무 없어 다른 기능들을 사용하기 쉽지 않으며, 필요성이 아직 높지 않아 추후 진행할 예정이다.


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/slides.googleapis.com-python-quickstart.json

SCOPES = 'https://www.googleapis.com/auth/presentations'

CLIENT_SECRET_FILE = 'client_slide.json'

APPLICATION_NAME = 'Google Slides API 4 Python'



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,

                                   'slides.googleapis.com-python-slide.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 Slides API.


    Creates a Slides API service object and prints the number of slides and

    elements in a sample presentation:

    https://docs.google.com/presentation/d/1EAYk18WDjIG-zp_0vLm3CsfQh_i8eXc67Jo2O9C6Vuc/edit

    """

    credentials = get_credentials()

    http = credentials.authorize(httplib2.Http())

    service = discovery.build('slides', 'v1', http=http)

    page_id = "test1234"

    presentationId = '사용할 슬라이드 id'

    requests = [

        {

            'createSlide': {

                'objectId': page_id,

                'insertionIndex': '1',

                'slideLayoutReference': {

                    'predefinedLayout': 'TITLE'

                }

            }

        }

    ]


# If you wish to populate the slide with elements, add element create requests here,

# using the page_id.


# Execute the request.

    body = {

        'requests': requests

    }

    response = service.presentations().batchUpdate(presentationId=presentationId, body=body).execute()

    create_slide_response = response.get('replies')[0].get('createSlide')

    print('Created slide with ID: {0}'.format(create_slide_response.get('objectId')))

    #slides = presentation.updateTableCellProperties()


    #print ('The presentation contains {} slides:'.format(len(slides)))

    #for i, slide in enumerate(slides):

    #    print('- Slide #{} contains {} elements.'.format(i + 1,

    #        len(slide.get('pageElements'))))


if __name__ == '__main__':

    main()

lispro06 (비회원)
  • 6
    • 글자 크기
[Gdata] sheetsChart creation for Python with Multi oAuth (by lispro06) [Gdata] API v4 사용 for Python (by lispro06)

댓글 달기

첨부 (6)
1.JPG
37.2KB / Download 66
2.JPG
29.8KB / Download 63
3.JPG
53.3KB / Download 59
4.JPG
34.9KB / Download 71
5.JPG
32.3KB / Download 60
6.JPG
43.1KB / Download 61
위로