[Google API] Google Docs API 로 문서 작성하기

재현·2021년 10월 29일
0
post-thumbnail

안내문

이 글은 Google Docs API 를 이용하여 문서를 작성하는데 도움을 주는 글 입니다.
반복적인 작업에 유용합니다!
저는 데일리 업무 중 시험지를 작성해야하는 일이 있었는데 이를 이용하여
소요 시간의 70%를 줄이게 되었습니다!

❗️❗️❗️

Google Cloud Platform 설정 내용은 없습니다.
(사용자 인증정보, API 라이브러리 설정, OAuth 동의 설정 SKIP)
Python 언어를 이용합니다.

목차

  1. Token 얻기
    1-1. Step 2: Configure the sample, 설정하기

  2. create Document
    2-1. SCOPES 설정

  3. 기존 문서 수정하기(batchUpdate)
    3-1. insert Text
    3-2. insert Image

1. Token 얻기

https://developers.google.com/docs/api/quickstart/python

구글에서 제공하는 공식 docs API 문서입니다.
위 링크를 참고하여 1번 ~ 3번 스탭 진행

1-1. Step 2: Configure the sample, 설정하기

  1. 프로젝트 폴더 생성
  2. 프로젝트 폴더/원하는 파일명.py 생성
  3. Document_ID = "OAuth2.0 클라이언트 ID"
  4. 파일 실행
  5. 폴더 내 token 생성

2. create Document

# build() 를 쓰기 위해 googleapiclient.discovery 에서 import
from googleapiclient.discovery import build

# os.path.exists() 를 쓰기위해 import
# 현재 파일이 위치한 경로
import os.path

# Credentials : google console - 사용자 인증정보 - OAuth 2.0 클라이언트 ID 
# 실행 파일(ex. main.py) 와 같은 위치에 있어야함
# 기존 client ID 는 숫자, 영문 그리고 특수기호로 이루어져있는데 이를 credentials.json 로 교체
from google.oauth2.credentials import Credentials

SCOPES = [    
    "https://www.googleapis.com/auth/documents",
    "https://www.googleapis.com/auth/drive",
    "https://www.googleapis.com/auth/drive.file", 
]

# exists() 를 이용해 동일 폴더 내 token.json 파일이 존재하는 지 확인
# 있을 시 cres 는 Credentials class 의 from_authorized_user_file("token.json, SCOPES") 로 선언됨 
if os.path.exists("token.json"):
    creds = Credentials.from_authorized_user_file("token.json", SCOPES)

# build() 를 통해 service 변수 선언
service = build("docs", "v1", credentials=creds)

title = 'My Document'

# JSON 형식으로 body 변수 선언
body = {
    "title": title
}

# 위 문서 실행문
doc = service.documents().create(body=body).execute()


2-1. SCOPES 설정

SCOPES = [    
    "https://www.googleapis.com/auth/documents",
    "https://www.googleapis.com/auth/drive",
    "https://www.googleapis.com/auth/drive.file", 
]

1) SCOPES 란

Google API 사용 시 액세스 수준을 정함
SCOPES 를 통해 문서를 only read or read or delete 등 여러가지 작업을 수행할 수 있는 허가를 부여할 수 있음


2) 이 문서에서 적용한 SCOPES 알아보기

https://www.googleapis.com/auth/documents : Google 문서 문서를보고 관리합니다.
https://www.googleapis.com/auth/drive : 모든 Google 드라이브 파일을보고, 수정하고, 만들고, 삭제합니다.
https://www.googleapis.com/auth/drive.file : 이 앱으로 열거 나 만든 Google 드라이브 파일 및 폴더를보고 관리합니다.


3) SCOPES 더 알아보기!


3. 기존 문서 수정하기(batchUpdate)

batchUpdate : 기존 작성된 문서 수정

아래 코드에선 기존에 작성된 문서에 insert Text 하는 식으로 구성되어있다.
따라서 DOCUMENT_ID 는 기존 문서 링크를 확인해보면 알 수 있는데
https://docs.google.com/document/d/"DOCUMENT_ID"
이런 식으로 구성되어 있으니 각자 링크에 맞는 DOCUMENT_ID 를 선언하자.

3-1. insert Text

from googleapiclient.discovery import build
import os.path
from google.oauth2.credentials import Credentials

SCOPES = [    
    "https://www.googleapis.com/auth/documents",
    "https://www.googleapis.com/auth/drive",
    "https://www.googleapis.com/auth/drive.file", 
]

DOCUMENT_ID = "작성된 기존 문서의 링크 확인"

if os.path.exists("token.json"):
    creds = Credentials.from_authorized_user_file("token.json", SCOPES)

service = build("docs", "v1", credentials=creds)


# JSON 형식으로 requests 선언
requests = [
    {
        'insertText': {
          # index 위치가 25번인 곳에 insertText
            'location': {
                'index': 25,
            },
            'text': text1
        }
    }
]

result = service.documents().batchUpdate(
documentId=DOCUMENT_ID, body={'requests': requests}).execute()

3-2. insert Image

from googleapiclient.discovery import build
import os.path
from google.oauth2.credentials import Credentials

SCOPES = [    
    "https://www.googleapis.com/auth/documents",
    "https://www.googleapis.com/auth/drive",
    "https://www.googleapis.com/auth/drive.file", 
]

DOCUMENT_ID = "작성된 기존 문서의 링크 확인"
  
if os.path.exists("token.json"):
    creds = Credentials.from_authorized_user_file("token.json", SCOPES)

service = build("docs", "v1", credentials=creds)

requests = [{
    'insertInlineImage': {
        'location': {
            'index': 1
        },
        'uri':
            'https://fonts.gstatic.com/s/i/productlogos/docs_2020q4/v6/web-64dp/logo_docs_2020q4_color_1x_web_64dp.png',
        'objectSize': {
            'height': {
                'magnitude': 50,
                'unit': 'PT'
            },
            'width': {
                'magnitude': 50,
                'unit': 'PT'
            }
        }
    }
}]

body = {'requests': requests}
response = service.documents().batchUpdate(
    documentId=DOCUMENT_ID, body=body).execute()
profile
Do Work As We & Respect 🙆🏾 🙆🏻‍♂️ 🙆🏻‍♀️ 🙆‍♀️

0개의 댓글