Created
July 25, 2019 06:45
-
-
Save ryumei/e4934bf3cf4b55963ec8ac5f7491cc54 to your computer and use it in GitHub Desktop.
Post Qiita article via API
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# -*- coding: utf-8 -*- | |
# | |
# Update an article via Qiita API | |
# Require: requests and toml (via pip) | |
# | |
import sys | |
import os | |
import logging | |
import json | |
import toml | |
import requests | |
QIITA_URL = 'https://qiita.com/api/v2/items' | |
TAGS = ["qiita_id", "title", "tags"] | |
def parse(filepath, max_header_lines=10): | |
u'''Parse original article (Hugo format)''' | |
title = None | |
qiita_id = None | |
tags = [{"name": "api", "version": []}] | |
body = '' | |
line_count = 0 | |
with open(filepath) as f: | |
in_header = False | |
header_toml = "" | |
for line in f: | |
line_count += 1 | |
if line.startswith('+++'): | |
if not in_header: | |
in_header = True | |
continue | |
else: | |
in_header = False | |
break | |
header_toml += line | |
conf = toml.loads(header_toml) | |
if 'tags' in conf: | |
for t in conf['tags']: | |
tags.append({"name": t, "version": []}) | |
if 'qiita_id' not in conf: | |
return None | |
for line in f: | |
body += line | |
return { | |
'title': conf['title'], | |
'qiita_id': conf['qiita_id'], | |
'tags': tags, | |
'body': body, | |
'tweet': False, | |
'private': False, | |
} | |
def submit(item, token, url=QIITA_URL, article_id=None): | |
u'''Submit to Qiita v2 API''' | |
headers = { | |
'Content-Type': 'application/json', | |
'Authorization': 'Bearer {}'.format(token) | |
} | |
if article_id is None or article_id == '': | |
res = requests.post(url, headers=headers, json=item) | |
else: | |
url = "{}/{}".format(url, article_id) | |
res = requests.patch(url, headers=headers, json=item) | |
if res.status_code >= 400: | |
logging.error(res.json()) | |
res.raise_for_status() | |
logging.info(json.dumps(res.json(), indent=2)) | |
return res | |
def execute(filepath, token): | |
item = parse(filepath) | |
if item is None: | |
logging.warning("SKIP. No qiita_id tag found.") | |
return | |
logging.debug(json.dumps(item, indent=2)) | |
res = submit(item, token=token, article_id=item['qiita_id']) | |
if __name__ == "__main__": | |
logging.basicConfig(level=logging.DEBUG) | |
token = os.environ['QIITA_TOKEN'] | |
for arg in sys.argv[1:]: | |
execute(arg, token) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment