0

I've setup a webhook in Django to receive updates from Mailgun.

The mailgun POST payload is delivered to the webhook in the below format:

{
  “signature”:
  {
    "timestamp": "1529006854",
    "token": "a8ce0edb2dd8301dee6c2405235584e45aa91d1e9f979f3de0",
    "signature": "d2271d12299f6592d9d44cd9d250f0704e4674c30d79d07c47a66f95ce71cf55"
  }
  “event-data”:
  {
    "event": "opened",
    "timestamp": 1529006854.329574,
    "id": "DACSsAdVSeGpLid7TN03WA",
    // ...
  }
}

If I try and retrieve event parameter using the below code, I get an error saying TypeError: 'method' object is not subscriptable

@csrf_exempt
@require_POST
def mailgun(request):
    event_data = request.POST.get['event-data']['event']
    return HttpResponse(event_data, status=200)

Any help is appreciated.

Rutnet
  • 1,533
  • 5
  • 26
  • 48

2 Answers2

2

After a lot of troubleshooting, the answer was hidden in the StackOverflow link below. In Python 3.0 to Python 3.5.x, json.loads() will only accept a unicode string, so you must decode request.body (which is a byte string) before passing it to json.loads().

Trying to parse `request.body` from POST in Django

body_unicode = request.body.decode('utf-8')
body = json.loads(body_unicode)
content = body['event-data']
recipient = content['recipient']
Rutnet
  • 1,533
  • 5
  • 26
  • 48
0

Try to update .get to call function and add some input checks, ie:

if request.POST.get('event-data'):
    event_data = request.POST.get('event-data')['event']
    return HttpResponse(event_data, status=200)
else:
    return HttpResponse("[unknown event]", status=400)

or if you sure event-data never be empty or null call directly:

request.POST['event-data']['event']
ujlbu4
  • 1,058
  • 8
  • 8
  • If I run the first coomand, I get: TypeError: 'NoneType' object is not subscriptable – Rutnet Sep 07 '20 at 13:10
  • @Rutnet is it possible you receive `event-data` which is empty? – ujlbu4 Sep 07 '20 at 13:17
  • @Rutnet updated my answer with extended examples (with response with 400 status code if incoming data is not what you expected) – ujlbu4 Sep 07 '20 at 13:23
  • I think the event data is not being returned properly. This is the structure of the event_data https://documentation.mailgun.com/en/latest/user_manual.html#webhooks – Rutnet Sep 07 '20 at 13:31
  • okey, could you show ( `print(dict(request.POST))` ) what you actually receive from mailgun? – ujlbu4 Sep 07 '20 at 13:53
  • Let us [continue this discussion in chat](https://chat.stackoverflow.com/rooms/221108/discussion-between-ujlbu4-and-rutnet). – ujlbu4 Sep 07 '20 at 14:51