2017-07-08 204 views
0

我試圖建立一個webhook,接收來自第三方服務Messagebird的JSON POST。在他們的文檔,他們曾傳出查詢的例子:解析傳入Webhook的JSON

GET http://your-own.url/script 
    ?id=e8077d803532c0b5937c639b60216938 
    &recipient=31642500190 
    &originator=31612345678 
    &body=This+is+an+incoming+message 
    &createdDatetime=2016-05-03T14:26:57+00:00 

我的網絡掛接正在使用Python內置Django的,這就是我在我的views.py:

from django.shortcuts import render 
from django.views.decorators.http import require_POST 
from django.http import HttpResponse 
from .models import UserText 

@require_POST 
def webhookmb(request): 
    usrtxt = json.loads(request.body.decode("utf-8")) 

    UserText.objects.create(
     id = usrtxt['id'] 
     recipient = usrtxt['recipient'] 
     originator = usrtxt['originator'] 
     body = usrtxt['body'] 
     createdDatetime = usrtxt['createdDatetime'] 
    ) 

    return HttpResponse(200) 

我的目標將JSON讀入文件usrtxt,然後將這些字段映射到模型。我得到這個錯誤(部署在Heroku):

JSONDecodeError: Expecting value: line 1 column 1 (char 0)

這是因爲json.loads試圖讀取文件和第一像開始與GET?我需要跳過這一行嗎?還是有另一種方式去解決這個問題?

回答

0

這看起來可能過於簡單,但可以在您的webhook上添加@csrf_exempt裝飾器。