LoginSignup
2
3

More than 3 years have passed since last update.

FlaskとDjangoのJSONデータの受け取り方の違いにハマる

Posted at

こんばんは、@0yanです。
今日はLINE WORKS版Trello BotのFlaskアプリを、LINE WORKS問い合わせ対応BotのDjangoアプリに統合する際、JSONデータの受け取り方の違いにハマった(ダサイ・・・)ので、しくじり先生的な感じで記事書きます。
※LINE WORKS版Trello Botの作成方法はこちら

Flaskの場合

data = request.json['key']で、辞書型の値として受け取れます。

具体例(Flaskの場合)
@app.route('/webhook', methods=['HEAD', 'POST'])
def comment_notification_to_talk_room():
    if request.method == 'HEAD':
        return '', 200
    elif request.method == 'POST':
        action_type = request.json['action']['display']['translationKey']  # ★ココ
        if action_type == 'action_comment_on_card':
            card_name = request.json['action']['data']['card']['name']
            user_name = request.json['action']['memberCreator']['fullName']
            comment = request.json['action']['data']['text']
            message = f'{user_name}さんがコメントしました。\n【カード】{card_name}\n【コメント】{comment}'
            talk_bot.send_text_message(send_text=message)
            return '', 200
    else:
        abort(400)

Djangoの場合

body = json.loads(request.body)のように、JSONから辞書型に変換する必要があります。

具体例(Djangoの場合)
def comment_notification_to_talk_room(request, bot_no, account_id=None, room_id=None):
    talk_bot = TalkBotApi(api_id, server_api_consumer_key, server_id, private_key, domain_id, bot_no)

    # リクエストボディをJSONから辞書型に変換、action_typeを取り出す
    body = json.loads(request.body)  # ★ココ
    action_type = body['action']['display']['translationKey']

    # TrelloのコメントをLINE WORKSトークルームに送信
    if action_type == 'action_comment_on_card':
        card_name = body['action']['data']['card']['name']
        user_name = body['action']['memberCreator']['fullName']
        comment = body['action']['data']['text']
        message = f'{user_name}さんがコメントしました。\n【カード】{card_name}\n【コメント】{comment}'
        if account_id is not None:
            talk_bot.send_text_message(send_text=message, account_id=account_id)
            logger.info(f'通知成功  accountID:{account_id}')
        elif room_id is not None:
            talk_bot.send_text_message(send_text=message, room_id=room_id)
            logger.info(f'通知成功  roomID:{room_id}')
        else:
            logger.error('accoutId, roomIdはどちらか一方を指定する必要があります。')

いやー、こんなくだらないことに数時間使ってしまうとは・・・。
この失敗が誰かの役に立つことを願っています。

2
3
0

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
3