スイッチIoTで服薬管理 〜M5Stack × AWS〜 [Part2] | 服薬カレンダー(2/3)

バックエンド処理の開発

AWS Lambda」を使って、APIルート毎のバックエンド処理をプログラミングします。


AWSのLambdaコンソールにサインインして、前回と同様に[関数の作成]ボタンを選択します。 今回の関数名は「medication-calendar-function」としましょう。
  1. 💡 おさらい:細かい手順はこちらをチェック!
    スイッチIoTで服薬管理 〜M5Stack × AWS〜 [Part1] | 服薬カウンター
     ➡ ■バックエンド処理の開発

服薬カレンダーのバックエンド処理として作成したソースがこちらです。
lambda_function.py
import json
import calendar
import boto3
from boto3.dynamodb.conditions import Key
from datetime import timedelta, date

dynamo = boto3.resource('dynamodb')
table = dynamo.Table('medication-management-table')

def lambda_handler(event, context):
    statusCode = 200
    responseBody = {}

    # ルートキーの取得
    routeKey = event['routeKey']

    try:
        if routeKey == 'GET /calendar/{year}/{month}':
        # 服薬カレンダー取得のGET APIがコールされた場合

            # パスパラメータ取得
            year = int(event['pathParameters']['year'])         # 年
            month = int(event['pathParameters']['month'])       # 月

            # 対象月のカレンダー情報を取得 
            monthCalendarList = calendar.monthcalendar(year, month)

            # 1か月分データリストを生成(空データ)
            monthDataList = []

            # 1か月分のカレンダー情報をループ
            for weekCalendarList in monthCalendarList:

                # 1週間分データリストを生成(空データ)
                weekDataList = []

                # 1週間分のカレンダー情報をループ
                for day in weekCalendarList:

                    count = 0
                    if day > 0:
                        # 対象日のデータ件数を取得
                        yyyymmdd = str(year) + str(month).zfill(2) + str(day).zfill(2)

                        # queryメソッドで指定日付のデータを作成
                        data = table.query(
                            KeyConditionExpression = Key('yyyymmdd').eq(yyyymmdd)
                        )

                        # データ件数を取得
                        count = data['Count']

                    # 日別件数データを作成
                    dict = {
                        'day' : day,        # 日
                        'count' : count     # 件数
                    }

                    # 日別件数データを1週間分データリストに追加
                    weekDataList.append(dict)

                # 1週間分データリストを1か月分データリストに追加
                monthDataList.append(weekDataList)

            # レスポンスボディに取得結果をJSON形式でセット
            res = {
                'yyyymm': str(year) + '/' + str(month).zfill(2),    # 表示年月
                'data': monthDataList                               # 1か月分データリスト
            }
            responseBody = json.dumps(res)

    except Exception as e:
        # エラーが起きた時の処理
        print(e)
        statusCode = 500
        responseBody = json.dumps('エラー発生')

    # レスポンス返却
    return {
        'statusCode' : statusCode,
        'body' : responseBody,
        'headers' : {
            'Content-Type': 'application/json'
        }
    }

ポイント解説

カレンダー情報の取得
import calendar
・・・

# 対象月のカレンダー情報を取得 
monthCalendarList = calendar.monthcalendar(year, month)
今回のポイントは「カレンダー情報の取得」、これに尽きます。
Pythonにはcalendarモジュールという便利な標準ライブラリが備わっています。
calendar.monthcalendarメソッドで、対象月のカレンダー情報をリストで取得できます。

どのような情報が得られるのか、printした結果が以下です。
monthCalendarList = calendar.monthcalendar(2023, 7)
print(monthCalendarList)

【print結果】
[[0, 0, 0, 0, 0, 1, 2], [3, 4, 5, 6, 7, 8, 9], [10, 11, 12, 13, 14, 15, 16], [17, 18, 19, 20, 21, 22, 23], [24, 25, 26, 27, 28, 29, 30], [31, 0, 0, 0, 0, 0, 0]]

縦に並べると、カレンダーっぽく見えるでしょうか。
1週間毎に月曜日から日曜日の日付が並んでおり、対象月以外の箇所には0が設定されます。
第1週:[0, 0, 0, 0, 0, 1, 2]
第2週:[3, 4, 5, 6, 7, 8, 9]
第3週:[10, 11, 12, 13, 14, 15, 16]
第4週:[17, 18, 19, 20, 21, 22, 23]
第5週:[24, 25, 26, 27, 28, 29, 30]
第6週:[31, 0, 0, 0, 0, 0, 0]

1か月分のカレンダー情報が取得できれば、リストをループしながら、対象日の服薬記録件数をデータベースから取得していきます。


Web APIのルートとバックエンド処理の接続

AWSのAPI Gatewayコンソールにサインインして、「服薬カレンダー取得API」のルートとLambda関数を接続します。
GET /calendar/{year}/{month}」のルートにLambada関数「medication-calendar-function」の統合設定を作成しアタッチします。
  1. 💡 おさらい:細かい手順はこちらをチェック!
    スイッチIoTで服薬管理 〜M5Stack × AWS〜 [Part1] | 服薬カウンター
     ➡ ■Web APIのルートとバックエンド処理の接続

あなたへのおすすめ記事