[PYTHON] I'm addicted to the difference in how Flask and Django receive JSON data

Good evening, this is @ 0yan. Today, when I integrated the Flask app of the LINE WORKS version of Trello Bot into the Django app of the Bot that supports LINE WORKS inquiries, I was addicted to the difference in how to receive JSON data (Dasai ...). write.

For Flask

You can receive it as a dictionary type value with data = request.json ['key'].

Specific example (in the case of 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']  #β˜… Coco
        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}Commented.\n [card]{card_name}\n [Comment]{comment}'
            talk_bot.send_text_message(send_text=message)
            return '', 200
    else:
        abort(400)

For Django

You need to convert from JSON to dictionary type, like body = json.loads (request.body).

Specific example (for 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)

    #Convert request body from JSON to dictionary type, action_Extract type
    body = json.loads(request.body)  #β˜… Coco
    action_type = body['action']['display']['translationKey']

    #Send Trello's comments to the LINE WORKS talk room
    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}Commented.\n [card]{card_name}\n [Comment]{comment}'
        if account_id is not None:
            talk_bot.send_text_message(send_text=message, account_id=account_id)
            logger.info(f'Notification success accountID:{account_id}')
        elif room_id is not None:
            talk_bot.send_text_message(send_text=message, room_id=room_id)
            logger.info(f'Notification successful roomID:{room_id}')
        else:
            logger.error('accoutId,You need to specify either roomId.')

No, I would spend a few hours doing such a silly thing ... I hope this failure helps someone.

Recommended Posts

I'm addicted to the difference in how Flask and Django receive JSON data
How to return the data contained in django model in json format and map it on leaflet
How to get the date and time difference in seconds with python
How to count the number of elements in Django and output to a template
The first step to log analysis (how to format and put log data in Pandas)
How to use argparse and the difference between optparse
POST the image with json and receive it with flask
How to use Decorator in Django and how to make it
How to write custom validations in the Django REST Framework
How to generate a query using the IN operator in Django
How to get all the keys and values in the dictionary
In Django, how to abbreviate the long displayed string as ....
How to reflect CSS in Django
How to give and what the constraints option in scipy.optimize.minimize is
Difference in how to write if statement between ruby ​​and python
How to display bytes in the same way in Java and Python
How to divide and process a data frame using the groupby function
How to check the version of Django
How to write the correct shebang in Perl, Python and Ruby scripts
How to delete expired sessions in Django
Send and receive image data as JSON over the network with Python
The file name was bad in Python and I was addicted to import
How to do Server-Sent Events in Django
How to convert DateTimeField format in Django
How to deal with garbled characters in json of Django REST Framework
How to copy and paste the contents of a sheet in Google Spreadsheet in JSON format (using Google Colab)
How to use is and == in Python
How to make only one data register on the Django admin screen
(Diary 1) How to create, reference, and register data in the SQL database of Microsoft Azure service with python
I want to visualize where and how many people are in the factory
How to pass the path to the library built with pyenv and virtualenv in PyCharm
How to uniquely identify the source of access in the Django Generic Class View
[Python] How to name table data and output it in csv (to_csv method)
How to use the C library in Python
How to receive command line arguments in Python
How to generate permutations in Python and C ++
How to implement Rails helper-like functionality in Django
Just add the python array to the json data
Receive and display HTML form data in Python
How to reflect ImageField in Django + Docker (pillow)
How to run some script regularly in Django
[Django] How to get data by specifying SQL.
[Python] How to read data from CIFAR-10 and CIFAR-100
About the difference between "==" and "is" in python
[Introduction to Python] How to handle JSON format data
How to print debug messages to the Django console
I'm addicted to Kintone as a data store
How to create data to put in CNN (Chainer)
How to get the files in the [Python] folder
Sample API server to receive JSON in Golang
How to read time series data in PyTorch
POST JSON in Python and receive it in PHP
How to create a Rest Api in Django
Data cleaning How to handle missing and outliers
How to write async and await in Vue.js
Use pygogo to get the log in json.
How to plot autocorrelation and partial autocorrelation in python
How to split machine learning training data into objective variables and others in Pandas
How to use fixture in Django to populate sample data associated with a user model
[Note] How to write QR code and description in the same image with python
I just wanted to extract the data of the desired date and time with Django