2
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

[Python]Qiita APIとテンプレートエンジンJinja2で記事を投稿する

Last updated at Posted at 2021-09-20

はじめに

本記事では、Qiita APIでの記事投稿の際に記事本文にPythonのテンプレートエンジンであるJinja2の出力を利用する方法を紹介します。
本記事自身をQiita APIとJinja2テンプレートを使って投稿しています。

テンプレートの準備

template.md.j2というファイル名のJinja2に使うテンプレートを用意します。
本記事では、記事一覧表示のサンプル部分の表を変数で埋め込みます。

記事一覧表示のサンプル

自分の投稿記事一覧を取得して、表形式で表示します。

実行結果

No 記事
1 Qiitaの類似記事を見つける(TF-IDF+コサイン類似度)
2 iPadからVSCodeとJupyter Notebookを使う
3 VPSのDocker上のアプリにアクセス制限をかける
4 【Java】Apache HttpClientの使い方メモ
5 Qiita APIでの投稿記事取得のページネーション実装2種(Python)
6 QiitaのSelenium全記事からワードクラウドを作る
7 Ubuntu 20.04のdocker build時にタイムゾーン選択を求められた時の対処メモ
8 Selenium(Python)の個人的スニペット集
9 [Chrome] SeleniumでBasic認証を突破する
10 SeleniumでWeb監視をしてLINEに通知する
11 SeleniumとHeadless ChromeでページをPDFに保存する
12 【Selenium】Googleスプレッドシートを読み込んで会員登録フォームに入力する
13 【Chrome】Seleniumでページ全体のスクリーンショットを撮る
14 Seleniumでクリック前に要素にスクロールさせる
15 SelenideでSeleniumのテスト用サイトをテストしてみる
16 Selenide + Allureでクリック毎にスクリーンショットを取得して、テストレポートに添付する
17 Selenium + Headless Chrome + Jupyter Notebook + Docker

テンプレート部分

テンプレート

| No | 記事 |
|:-----------|:------------|
{% for article in sample_articles -%}
| {{ loop.index }} | [{{ article.title }}]({{ article.url }}) |
{% endfor %}

記事一覧の取得

Qiita APIを使って記事を取得するPythonコードは以下を使っています。

記事一覧の取得
# Qiita APIを利用して、記事を取得する
def get_articles(query = None):
    ret = []
    # クエリパラメータの準備
    params = {
        'page': '1',
        'per_page': '100'
    }
    if (query is not None):
        params['query'] = query
    req_headers = {}

    url = "https://qiita.com/api/v2/items?" + urllib.parse.urlencode(params)
    # Qiita APIから結果を取得
    req = urllib.request.Request(url, headers=req_headers)
    with urllib.request.urlopen(req) as res:
        body = json.load(res)
        for article in body:
            ret.append({"url": article["url"], "title": article["title"]})

    return ret

テンプレートエンジンでの本文作成

Jinja2を使ったMarkdown形式の投稿本文作成部分のPythonコードは以下です。

本文作成
# Jinja2を使って、投稿記事の本文を生成する
def create_article_content(sample_articles):
    env = Environment(loader=FileSystemLoader('.'))
    template = env.get_template('template.md.j2')
 
    data = {'sample_articles': sample_articles}
    markdown_text = template.render(data)
    return markdown_text

記事投稿

Qiita APIを使って記事を投稿するPythonコードは以下を使っています。

記事の投稿
# Qiita APIを利用して、記事を投稿する
# 以下では、「"private": True」として、限定共有状態で投稿します
def post_article(token, content):
    url = 'https://qiita.com/api/v2/items'
    data = {
        "body": content,
        "private": True,
        "tags": [
            {
                "name": "Qiita"
            },
            {
                "name": "QiitaAPI"
            },
            {
                "name": "Python"
            },
            {
                "name": "jinja2"
            }
        ],
        "title": "[Python]Qiita APIとテンプレートエンジンJinja2で記事を投稿する",
    }
    headers = {
        'Content-Type': 'application/json',
        'Authorization': 'Bearer ' + token
    }

    req = urllib.request.Request(url, json.dumps(data).encode(), headers)
    try:
        with urllib.request.urlopen(req) as res:
            body = json.load(res)
            print("投稿記事URL: " + body["url"])
    except urllib.error.HTTPError as err:
            print(err.code)
    except urllib.error.URLError as err:
            print(err.reason)

メイン関数

ここまでを合わせたPythonのメイン関数部分は、以下のようになります。

メイン関数
def main():
    # 自分の投稿記事を取得
    sample_articles = get_articles('user:mochi_yu2')
    # 投稿記事のMarkdown形式の本文をJinja2で生成
    content = create_article_content(sample_articles)
    # Qiitaに投稿
    post_article(ACCESS_TOKEN, content)

if __name__ == "__main__":
    main()

参考

本記事の作成にあたり以下の記事を参考にさせていただきました。

付録: Pythonコード全体

post_article.py
import urllib.request
import json
from jinja2 import Template, Environment, FileSystemLoader

# Qiita APIのアクセストークン
ACCESS_TOKEN = 'YOUR ACCESS_TOKEN'

# Qiita APIを利用して、記事を取得する
def get_articles(query = None):
    ret = []
    # クエリパラメータの準備
    params = {
        'page': '1',
        'per_page': '100'
    }
    if (query is not None):
        params['query'] = query
    req_headers = {}

    url = "https://qiita.com/api/v2/items?" + urllib.parse.urlencode(params)
    # Qiita APIから結果を取得
    req = urllib.request.Request(url, headers=req_headers)
    with urllib.request.urlopen(req) as res:
        body = json.load(res)
        for article in body:
            ret.append({"url": article["url"], "title": article["title"]})

    return ret

# Qiita APIを利用して、記事を投稿する
# 以下では、「"private": True」として、限定共有状態で投稿します
def post_article(token, content):
    url = 'https://qiita.com/api/v2/items'
    data = {
        "body": content,
        "private": True,
        "tags": [
            {
                "name": "Qiita"
            },
            {
                "name": "QiitaAPI"
            },
            {
                "name": "Python"
            },
            {
                "name": "jinja2"
            }
        ],
        "title": "[Python]Qiita APIとテンプレートエンジンJinja2で記事を投稿する",
    }
    headers = {
        'Content-Type': 'application/json',
        'Authorization': 'Bearer ' + token
    }

    req = urllib.request.Request(url, json.dumps(data).encode(), headers)
    try:
        with urllib.request.urlopen(req) as res:
            body = json.load(res)
            print("投稿記事URL: " + body["url"])
    except urllib.error.HTTPError as err:
            print(err.code)
    except urllib.error.URLError as err:
            print(err.reason)

# Jinja2を使って、投稿記事の本文を生成する
def create_article_content(sample_articles):
    env = Environment(loader=FileSystemLoader('.'))
    template = env.get_template('template.md.j2')
 
    data = {'sample_articles': sample_articles}
    markdown_text = template.render(data)
    return markdown_text

def main():
    # 自分の投稿記事を取得
    sample_articles = get_articles('user:mochi_yu2')
    # 投稿記事のMarkdown形式の本文をJinja2で生成
    content = create_article_content(sample_articles)
    # Qiitaに投稿
    post_article(ACCESS_TOKEN, content)

if __name__ == "__main__":
    main()
2
1
2

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?