📧

未使用のSendGridテンプレートを抽出する方法

2023/09/19に公開

課題

SendGridテンプレートを整理する際、テンプレートIDを1つ1つクリップボードにコピーしてプロジェクトディレクトリ内で参照されているかサーチすると時間が掛かる上に事故が起こりやすい。

要約

Pythonプログラムを用意して上記手順を自動実行する。

必要なもの

  • SendGrid API キーの値(SG.xxxxxxx.xxxxxxxxxxxxxx)
  • プロジェクトディレクトリ

手順

以下のシェルスクリプトを実行してローカル環境に全テンプレート情報を取得する。

% curl -X GET "https://api.sendgrid.com/v3/templates?generations=dynamic" -H "Authorization: Bearer SG.xxxxxxx.xxxxxxxxxxxxxx" > templates.json

以下のように全テンプレートの情報がJSON形式で保存される。

{
  "templates": [
    {
      "id": "d-xxxxxxxxxxx",
      "name": "entry-complete",
      "generation": "dynamic",
      "updated_at": "2023-09-06 06:46:35",
      "versions": [
        {
          "id": "xxxxxx-xxxxx-xxxxx",
          "template_id": "d-xxxxxxxxxxx",
          "active": 1,
          "name": "entry-complete",
          "generate_plain_content": true,
          "subject": "会員登録完了",
          "updated_at": "2023-09-06 06:49:42",
          "editor": "code",
          "thumbnail_url": ""
        }
      ]
    },
    {
      "id": "d-xxxxxxxxxxx",
      "name": "contact-complete",
      "generation": "dynamic",
      "updated_at": "2023-09-06 06:46:35",
      "versions": [
        {
          "id": "xxxxxx-xxxxx-xxxxx",
          "template_id": "d-xxxxxxxxxxx",
          "active": 1,
          "name": "contact-complete",
          "generate_plain_content": true,
          "subject": "問い合わせ完了",
          "updated_at": "2023-09-06 06:49:42",
          "editor": "code",
          "thumbnail_url": ""
        }
      ]
    }
  ]
}

自動実行用のPythonプログラムファイルを作成する。

import json
import subprocess

# SendGridのテンプレート情報を含むJSONファイルを読み込む
with open('templates.json', 'r') as f:
    templates = json.load(f)

unused_templates = []

# 各テンプレートに対してgrepを実行
for template in templates.get('templates', []):
    template_id = template['id']
    result = subprocess.run(
        ['grep', '-rl', template_id, './vaundy/sources/app'], capture_output=True, text=True)

    # grepの結果が空の場合、そのテンプレートIDは使用されていない
    if not result.stdout:
        unused_templates.append(template_id)

print("Unused template IDs:")
for template_id in unused_templates:
    print(template_id)

Pythonプログラムを実行する。

未使用のテンプレートIDだけが出力される。

t-tomo :: ~ » python3 search_unused_templates.py

Unused template IDs:
d-xxxxxxxxxx1
d-xxxxxxxxxx2
d-xxxxxxxxxx3
t-tomo :: ~ »

ポイント

プロジェクトディレクトリの指定時にライブラリやフレームワークの階層を含むとサーチ(grep)に時間が掛かるので注意

O-KUN Tech Blog

Discussion