My problem was similar. I got a payload
POST request when a user clicked a button
from my slackbot. The Content-Type
was application/x-www-form-urlencoded
. I used Flask, Python3.
I tried this solution and it didn't work
@app.route('/process_data', methods=['POST'])
def process_data():
req_data = request.get_json(force=True)
language = req_data['language']
return 'The language value is: {}'.format(language)
My solution 1 was:
from urllib.parse import parse_qs
# Some code
@ app.route('/slack/request_handler', methods=['POST'])
def request_handler():
# request.get_data() returned a bytestring
# parse_qs() returned a dict from a bytestring. This dict has 1 pair
# I tried payload_dict.keys() to see what keys in the dict and it had one key only
payload_dict = parse_qs(request.get_data())
# Get the value of the key from payload_dict
# Value of the key from payload_dict is an array, length = 1
payload_dict_value_arr = payload_dict[b'payload']
# Get data from the index[0] of the array payload_dict_value_arr
data = payload_dict_value_arr[0]
# convert a string (representation of a Dict)) to a Dict
# Note that if you have single quotes as a part of your keys or values this will
# fail due to improper character replacement.
# This solution is only recommended if you have a strong aversion
# to the eval solution.
datajson = json.loads(data)
# get value of key "channel"
channel = datajson["channel"]
print(channel) {'id': 'D01ACC2E8S3', 'name': 'directmessage'}
My solution 2, a bit shorter:
@ app.route('/slack/request_handler', methods=['POST'])
def request_handler():
payload = request.form # return an ImmutableMultiDict with 1 pair
a1 = payload['payload'] # get value of key 'payload'
# Note that if you have single quotes as a part of your keys or values this will
# fail due to improper character replacement.
# convert a string (representation of a Dict)) to a Dict
a2 = json.loads(a1)
# get value of key "channel"
channel = a2["channel"]
print(channel) # {'id': 'D01ACC2E8S3', 'name': 'directmessage'}
flask.Request.get_data
, Unicode in Flask