본문 바로가기
Programming/Python

[Python] 자격증 일정 구글 캘린더 API 연동 프로젝트 (3/4)

by JeeU147 2022. 5. 10.
반응형

안녕하세요.

 

오늘은 파이썬으로 자격증 일정 구글 캘린더 API 연동을 하는 프로젝트를 진행해보려고 합니다.

 

해당 게시글은 3번째 챕터의 글입니다.

 

처음부터 따라가셔야 진행이 됩니다.

 

첫번째 게시글의 링크를 달아놓았으니 참고바랍니다.

2022.05.06 - [프로그래밍/Python] - [Python] 자격증 일정 구글 캘린더 연동 프로젝트 (1/4)

 

[Python] 자격증 일정 구글 캘린더 연동 프로젝트 (1/4)

안녕하세요. 오늘은 파이썬으로 자격증 일정 구글 캘린더 연동을 하는 프로젝트를 진행해보려고 합니다. 준비물 Python 주피터 노트북 2021.10.28 - [프로그래밍/Python] - [Python] 윈도우에서 주피터 노

jeeu147.tistory.com

 

구글 캘린더 일정 추가
1. 첫번째 챕터와 두번째 챕터에서 나왔던 JSON파일들, 크롬 드라이버를 프로젝트와 같은 디렉토리에 놓습니다.

세번째 챕터에서는 해당 파일들의 경로 설정을 같은 디렉토리에 위치했을 경우로 코드를 짰습니다.

 

이후에 파일들을 따로 두고 싶으시다면 경로를 다시 설정하여 코드를 실행시키기 바랍니다.

 

디렉토리 설정

2. token.json

해당 파일은 구글 인증이 정상적으로 이루어졌다면 최초에 token(인증 파일)을 json으로 내려줍니다.

 

calendar_insert.py를 최초 실행 시 아래의 그림으로 액세스 요청을 합니다.

 

액세스 요청에 성공하면 "The authentication flow has completed. You may close this window." 이라는 문구와 함께 token.json 파일이 생성이 됩니다.

token.json 파일 생성

3. 코드 분석

먼저 코드를 한번 흝고 진행해보도록 하겠습니다. 코드는 깃허브에도 있으니 참고 부탁드립니다.

https://github.com/robot147/Google-Calendar

 

GitHub - robot147/Google-Calendar

Contribute to robot147/Google-Calendar development by creating an account on GitHub.

github.com

from bs4 import BeautifulSoup
from urllib.request import urlopen
from googleapiclient.discovery import build
from google_auth_oauthlib.flow import InstalledAppFlow
from google.auth.transport.requests import Request
from google.oauth2.credentials import Credentials

import json
import datetime
import os.path

# 자격명 입력
name = input("추가하고 싶은 자격명을 입력해주세요 : ")
jmCd = ""

with open('licenselist.json', 'r', encoding='utf-8') as f:
    json_data = json.load(f)

list = json.loads(json.dumps(json_data, ensure_ascii=False))

if name in list:
    jmCd = list[name]
else:
    print("자격명을 확인하여 다시 입력해주세요.")

# BeautifulSoup을 이용한 웹 크롤링 / jmCd는 자격명에 대한 각각의 고유값
response = urlopen('https://www.q-net.or.kr/crf005.do?id=crf00503s02&gSite=Q&gId=&jmCd=' + jmCd)
soup = BeautifulSoup(response, 'html.parser')
result = []
list = ["필기 원서 접수", "필기 시험", "필기 합격", "실기 원서 접수", "실기 시험", "실기 합격"]

def key(index, data):
    if index == 0:
        dic["회차"] = data.split()[len(data.split())-1]
    elif index == 1:
        dic["필기 원서 접수"] = data
    elif index == 2 :
        dic["필기 시험"] = data
    elif index == 3 :
        dic["필기 합격"] = data
    elif index == 4 :
        dic["실기 원서 접수"] = data.split()[0]
    elif index == 5 :
        dic["실기 시험"] = data
    elif index == 6 :
        dic["실기 합격"] = data

# 구글 캘린더에서는 날짜를 "-"로 써줘야함. eg) 2022-01-01
for data in soup.select(".tbl_normal table tbody > tr"):
    dic = {}
    str = ""
    for index in range(0, len(data.select("td"))):
        if "~" in data.select("td")[index].get_text().strip().split():
            for i in range(0, len(data.select("td")[index].get_text().strip().split())):
                str += data.select("td")[index].get_text().strip().split()[i]
                key(index, str.replace(".", "-"))
        else:
            key(index, data.select("td")[index].get_text().strip().replace(".", "-"))
    result.append(dic)

# 구글 계정 인증 절차
# from_client_secrets_file 함수를 통하여 OAuth JSON 파일로 token.json를 만들어 줍니다.
# json 파일 위치는 해당 py 파일과 같은 디렉토리에 넣으시면 됩니다.
# If modifying these scopes, delete the file token.json.
SCOPES = ['https://www.googleapis.com/auth/calendar']

"""Shows basic usage of the Google Calendar API.
Prints the start and name of the next 10 events on the user's calendar.
"""
creds = None
# The file token.json stores the user's access and refresh tokens, and is
# created automatically when the authorization flow completes for the first
# time.

# 기존에 token.json 파일이 있다면 기존 파일을 참조
if os.path.exists('token.json'):
    creds = Credentials.from_authorized_user_file('token.json', SCOPES)
# 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.json', 'w') as token:
        token.write(creds.to_json())

print("구글 계정 인증 완료")

# 서비스 객체 생성
service = build('calendar', 'v3', credentials=creds)

# 캘린더에 추가할 파라미터 생성 및 서비스 객체를 이용한 캘린더 추가
for data in result:
    for val in list:
        calendarData = {
            'summary': name + " " + data['회차'] + " " + val,  # 일정 제목
            # 'location': '서울특별시 용산구 한강대로 지하 392', # 일정 장소
            'description': name + " " + data['회차'] + " " + val,  # 일정 설명
            'start': {  # 시작 날짜 (몇시부터~ 일정을 넣고 싶으면 아래 dateTime으로 설정
                # 'dateTime': '2022-04-22T09:00:00',
                'timeZone': 'Asia/Seoul',
                'date': data[val] if len(data[val].split("~")) == 1 else data[val].split("~")[0] # 하루 종일
            },
            'end': {  # 종료 날짜 (~몇시까지 일정을 넣고 싶으면 아래 dateTime으로 설정)
                # 'dateTime': '2022-04-25T10:00:00',
                'timeZone': 'Asia/Seoul',
                'date': data[val] if len(data[val].split("~")) == 1 else data[val].split("~")[1] # 하루 종일
            },
            'transparency': 'transparent',
            'reminders': {  # 알림 설정
                'useDefault': False,
                'overrides': [
                    {'method': 'email', 'minutes': 15 * 60},  # 이메일로 알림이 수신됩니다. 24 * 60분 = 하루 전 알림 / 15 * 60 = 하루 전 오전 9시에 알림
                    {'method': 'popup', 'minutes': 15 * 60},  # 핸드폰 팝업으로 뜨게 됩니다.
                ],
            },
        }

        # calendarId : 캘린더 ID. primary이 자기 자신입니다. 다른 캘린더에 작성하고 싶다면 매뉴얼을 참조
        event = service.events().insert(calendarId='primary',
                                        body=calendarData).execute()

        print("Calendar Name : " + event['summary'] + ", Calendar Link : " + event['htmlLink'])

        print("캘린더 추가 완료")

필요 없는 부분이 있지만 주석으로 해당 부분 설명 달아놓았습니다.

 

※ 중요한 부분은 abc@gmail.com 이라는 계정으로 여러개의 캘린더를 사용할 수 있습니다.

 

abc@gmail.com이라는 계정으로만 사용하신다면 calendarId='primary' 로 하시면 되지만

 

다른 캘린더로 입력을 하고 싶다면 calendarId를 변경을 해주셔야 합니다.

 

calendarId 확인 방법

4. 캘린더 일정 추가 결과

해당 구글 캘린더 일정 추가 파이썬을 실행해주시면 아래와 같이 인풋 형식으로 추가하고 싶은 자격명을 입력해주세요 : 가 뜹니다.

 

원하는 자격증명을 입력해주시면 아래와 같이 로그가 남게됩니다.

CMD 실행

그리고 구글 캘린더에 정상적으로 입력이 되었는지 확인해줍니다!

구글 캘린더 일정 추가 완료

이렇게 해서 구글 캘린더에 정상적으로 일정들이 삽입이 되는걸 확인할 수 있습니다.

 

다음 챕터에서는 해당 자격 일정들을 삭제하는 API를 소개해드리면서 구글 캘린더 삭제하는 방법에 대해 알아보도록 하겠습니다.

 

궁금한 점 있으시면 댓글 달아주시기 바랍니다. 최대한 아는 범위 내에서 성심성의껏 답변 드리겠습니다.

 

감사합니다.

반응형

댓글