정보&강의 파이썬 티스토리 API를 이용하기 위한 access_token 발급과 사용 예제 소스
- 운영자
- 1606
- 7
첨부 1
- screenshot-www.tistory.com-2019.12.png (File Size: 227.7KB/Download: 1)
티스토리에 자동으로 글을 쓰고 싶어서 예제를 찾아봤는데, 제대로된 예제를 찾아보기 힘들었습니다.
티스토리 자체의 api 설명도 부족하구요.
일단 access token을 발급 받는 것 부터가 생소했는데, 1차로 인증 코드를 발급 받고, 2차로 access token 을 발급 받는 형식으로 전개 됩니다.
또 api 필드의 이름이 변경되었는데, 설명서와 api 등록 사이트의 필드 네임이 다른 경우가 있었습니다.
client id = app id 는 같은 의미이고, client secret = secret key와 같은 의미입니다.
저처럼 헷갈리는 분들은 참고하세요.
모든 조건이 맞았는데 오류가 날 때는 콜백 주소에서 마지막에 /를 빼고 시도해보길 바랍니다.
일반적으로 그냥 티스토리 주소를 넣으면 됩니다.
# coding=utf-8 import requests import webbrowser #client_id == app_id client_id = "" #client_secret = Secret_Key Secret_Key = "" #code는 access_token을 받기 위한 중간 인증코드, 나중에 사용하지 않음. code = "" #access_token는 이후에 모든 인증에서 사용하는 최종 키임. access_token = "" #티스토리 주소의 아이디나 전체주소 blog_name = "" #콜백주소는 자신의 티스토리 주소를 사용해도 되고, 끝에 /는 넣지 않는다. redirect_uri = "" state_param = "" output_type = "json" requests_headers = { "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/71.0.3578.98 Safari/537.36" } # 먼저 코드를 생성하고, if not code: auth_url = f'https://www.tistory.com/oauth/authorize?client_id={client_id}&redirect_uri={redirect_uri}&response_type=code&state={state_param}' webbrowser.open(auth_url) print('주소창에서 코드 값을 복사하세요. ?code= 이하') # 이후에 액세스 토큰을 받아야 한다. 이게 좀 귀찮고 낮설다. if not access_token: token_url = f'https://www.tistory.com/oauth/access_token?client_id={client_id}&client_secret={Secret_Key}&redirect_uri={redirect_uri}&code={code}&grant_type=authorization_code' webbrowser.open(token_url) r = requests.get(token_url) print(r.text) # 이제 실제 사용할 액세스 코드를 가지고 호출을 할 수 있다. def get_info(): info_url = f'https://www.tistory.com/apis/blog/info?access_token={access_token}&output={output_type}' r =requests.get(info_url, headers=requests_headers) return r.text def get_list(page_number): url = f'https://www.tistory.com/apis/post/list?access_token={access_token}&output={output_type}&blogName={blog_name}&page={page_number}' r = requests.get(url, headers=requests_headers) return r.text def get_category(): url = f'https://www.tistory.com/apis/category/list?access_token={access_token}&output={output_type}&blogName={blog_name}' r = requests.get(url, headers=requests_headers) r = r.json()['tistory']['item']['categories'] for i in r: print(f'{i["name"]} ({i["id"]})') return r def get_write(): title = "테스트" #제목 (필수) content = "글 내용" #글내용(필수) visibility = "3" #발행상태 0비공개-기본, 1보고,3발행 category_id = "0" #카테고리 아이디 기본값 0 slogan = "" #문자주소 tag = "" #태그 ,로 구분 acceptComment = "" #댓글 허용 (0, 1 - 기본값) password = "" #보호글 비밀번호 url = f'https://www.tistory.com/apis/post/write?access_token={access_token}&output={output_type}&blogName={blog_name}&title={title}&content={content}&visibility={visibility}&category={category_id}&slogan={slogan}&tag={tag}&acceptComment={acceptComment}&password={password}' r = requests.post(url) print(r, r.text) # https://iamaman.tistory.com/2084 def file_upload(): files = {'uploadedfile': open(filepath, 'rb')} params = {'access_token': token, 'blogName': blogName, 'targetUrl': blogName, 'output': 'json'} rd = requests.post('https://www.tistory.com/apis/post/attach', params=params, files=files) try: item = json.loads(rd.text) print(json.dumps(item, indent=4)) print("----------------------------------------------") print(item["tistory"]["replacer"]) print(item["tistory"]["url"]) print(item["tistory"]["status"]) except: print("Failed") get_category()
2020.6.15일 변경사항
400에러가 발생하면서 "access_token 이 유효하지 않습니다."라는 에러가 발생하는 경우에 대한 패치
원인, request로 처리하는 과정에서 해더 정보를 새롭게 체크하는 것 같습니다.
해당 해더 정보를 추가하면 됩니다.
requests_headers = {
"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/71.0.3578.98 Safari/537.36"
}
requests.get(url, headers=requests_headers)
이런 글도 찾아보세요!
댓글 7
주사랑
안녕하세요.
requests.get() 함수 사용시 headers=requests_headers 옵션을 추가하시면 됩니다.
소스에 반영하였습니다.
requests.get() 함수 사용시 headers=requests_headers 옵션을 추가하시면 됩니다.
소스에 반영하였습니다.
운영자
아... 운영자님 정말 감사합니다. 여기서 도움 정말 많이 받습니다... ㅠㅠ
한가지 더 말씀드릴건, post 로 보낼 때도 헤더가 필요하더군요. 파일업로드 소스도 헤더 없이는 동작을 안합니다. 이 부분도 수정이 필요할듯합니다.
그런데, 이 헤더의 역할이 어떤건지 알 수 있을까요? 기존에 안되던 것이 저걸 추가해서 되는게 이해가 잘 안가네요. 그리고 다른 API 의 경우에도 헤더가 필요하다면 똑같이 저 헤더를 넣으면 될까요? 아직 파이썬에 대해 모르는 부분이 너무 많습니다. ㅠ
한가지 더 말씀드릴건, post 로 보낼 때도 헤더가 필요하더군요. 파일업로드 소스도 헤더 없이는 동작을 안합니다. 이 부분도 수정이 필요할듯합니다.
그런데, 이 헤더의 역할이 어떤건지 알 수 있을까요? 기존에 안되던 것이 저걸 추가해서 되는게 이해가 잘 안가네요. 그리고 다른 API 의 경우에도 헤더가 필요하다면 똑같이 저 헤더를 넣으면 될까요? 아직 파이썬에 대해 모르는 부분이 너무 많습니다. ㅠ
주사랑
안녕하세요.
도움이 되셨다니 저도 기쁘네요.
헤더는 서버에서 신호를 확인하는 이름표같은 건데, 그동안 토큰만 확인하고 헤더값을 확인하지 않다가 최근에 확인하도록 수정된 거 같습니다.
모든 통신에 헤더값이 들어가야 정상이고, 말씀하신 파일처리 부분도 적용시키시는게 맞습니다.
파이썬으로 requests를 사용하시다가 보면 헤더 처리하는 부분이 자연스럽게 익혀지실거에요.
도움이 되셨다니 저도 기쁘네요.
헤더는 서버에서 신호를 확인하는 이름표같은 건데, 그동안 토큰만 확인하고 헤더값을 확인하지 않다가 최근에 확인하도록 수정된 거 같습니다.
모든 통신에 헤더값이 들어가야 정상이고, 말씀하신 파일처리 부분도 적용시키시는게 맞습니다.
파이썬으로 requests를 사용하시다가 보면 헤더 처리하는 부분이 자연스럽게 익혀지실거에요.
권한이 없습니다. 로그인
포스트맨이나 자바로 테스트 할 때는 문제가 없었는데 혹시 최근에 테스트해본적 있으신지요? 12일 이후로... 테스트 가능하실지 ㅠㅠ