ニュースで学ぶ「現代英語」の一覧を見やすくし、定期更新する by AWS

成果物

時系列順にやったこと

json特定

json to HTML

  • jsonを読んでHTMLをtableで組むPythonを書くだけ
  • (ここまではローカル環境で行った。自分用ならここまででいいが、一般的な内容・成果物なので公開もしてみよう)

AWS Lambdaで実行 & Layer設定

  • Lambdaの形式で書き直し、LambdaのページからDeploy & Test. しかしimport requestsが通らない
  • こういう外部パッケージを利用するにはLayer設定が必要
  • サラッと調べると「zipをUPして~」という記事が多く見つかるがイケてない
  • https://github.com/keithrozario/Klayers ここに書いてあるARNを指定すればいい
    • python versionとリージョンは合わせる必要がある
  • これでrequests, boto3のimportも通るようになった
  • add layerの方法は下記画像参照

python code (for Lambda)

import json
import datetime

import requests
import boto3

def lambda_handler(event, context):
    url = "https://www.nhk.or.jp/gogaku/gendaieigo/json/news.json"
    response = requests.get(url)
    json_data = response.json()

    html = "<table>"
    html += "<thead><tr><th>Title</th><th>Time</th></tr></thead>"
    html += "<tbody>"
    for article in json_data["news"]:
        title = article["title"]
        url = "https://www.nhk.or.jp/gogaku/gendaieigo/detail/index.html?no=" + article["no"]
        time = article["time"]
        html += f"<tr><td><a href='{url}'>{title}</a></td><td>{time}</td></tr>"
    html += "</tbody></table>"
    
    # date
    dt_now = datetime.datetime.now()
    html += "<br>last generated at " + str(dt_now) 
    
    # upload to S3
    s3 = boto3.client('s3')
    bucket_name = 'peroon-english'
    key_name = 'index.html'
    try:
        s3.put_object(Bucket=bucket_name, Key=key_name, Body=html, ContentType='text/html; charset=UTF-8')
    except Exception as e:
        error_text = f'Error uploading HTML file to S3: {str(e)}'
        html = error_text

    return {
        'statusCode': 200,
        'headers': {
            'Content-Type': 'text/html',
        },
        'body': html
    }

3秒ではタイムアウトする。10秒にせよ

  • lambdaの実行時間制限がデフォルト3秒だが、S3アクセスもあるのでタイムアウトした。10秒にすればいい

S3へのアクセス設定

Amazon EventBridgeで定期実行

  • Amazon CloudWatchでcron設定を進めていたと思ったらEventBridgeになっていた
  • cronの記法で時間を設定し、Lamdbaを指定すれば完了
  • 定期実行されていることを確認した✅

おまけ:予算アラート設定

追記:2022年分の記事終了

  • 告知通り、2023/5/8, 2022年分の記事が見えなくなりJSONからも削除された。大量に記事がある時に一覧性は光るので、少し残念

動画

2024/04/01 番組ページが終了

  • 「2024年4月1日10:00をもちまして、本ページの掲載を終了しました。」とのこと
  • 本+CD (or ダウンロード) という形式の方が、継続性では優れているね