728x90
- access_token의 발부를 전제로 함
- 향후 aws lambda로 확장성을 고려하여, 배포 후 설정이 변경될 부분에 대해서는 환경변수화
예제 코드
# %env access_token=...
# %env category=...
# %env visibility=0
# !echo $access_token $category $visibility
import requests
import os
class Tistory:
'''
티스토리 블로그 작성 자동화
https://tistory.github.io/document-tistory-apis/
'''
def __init__(self, access_token):
self.access_token = access_token
self.get_blog_name()
self.get_category_list()
@property
def default_params(self):
return {
'access_token': self.access_token,
'output': 'json',
}
def get_blog_name(self):
'''
블로그 이름 받기
https://tistory.github.io/document-tistory-apis/apis/v1/blog/list.html
'''
url = 'https://www.tistory.com/apis/blog/info'
response = requests.get(url, self.default_params)
data = response.json().get('tistory').get('item').get('blogs')[0]
self.blog_name = data.get('name')
print(f'blogName : {self.blog_name}')
def get_category_list(self):
'''
카테고리 목록 받기
https://tistory.github.io/document-tistory-apis/apis/v1/category/list.html
'''
url = 'https://www.tistory.com/apis/category/list'
params = dict(
blogName=self.blog_name,
**self.default_params
)
response = requests.get(url, params)
data = response.json().get('tistory').get('item').get('categories')
self.categories = [dict(id=d['id'], name=d['name']) for d in data]
print(f'categories : {self.categories}')
def write_post(self, title, content, *tag):
'''
글 작성 : `content`의 기본 설정이 `html`임을 유의
https://tistory.github.io/document-tistory-apis/apis/v1/post/write.html
'''
url = 'https://www.tistory.com/apis/post/write'
params = dict(
blogName=self.blog_name,
category=os.getenv('category'),
title=title,
content=content,
visibility=os.getenv('visibility'),
tag=','.join(tag[::-1]),
**self.default_params()
)
response = requests.post(url, params)
result = response.json().get('tistory').get('url')
print(result)
t = Tistory(os.getenv('access_token'))
t.write_post(
title='그대 곁의 그 사람 모르고 살겠죠',
content='''
<h1>누군가를 이렇게</h1>
<p>아프게 하는지</p>
'''
)
'Today_I_Learned' 카테고리의 다른 글
AWS API Gateway로 DynamoDB PutItem 메서드 구현 (23.10.13) (1) | 2023.10.14 |
---|---|
multiprocessing를 통한 병렬 처리 파이썬 코드 예제 (0) | 2023.09.30 |
네이버 증권 ETF 시세 정보 및 항목 리스트 API 조회 파이썬 코드 예제 (0) | 2023.09.30 |
장내채권 가격 데이터 조회 파이썬 코드 예제 (0) | 2023.09.29 |
Cloudflare R2 파일 업로드 파이썬 코드 예제 (0) | 2023.09.29 |