首页 > 解决方案 > 从 POST 请求中提取 json dict

问题描述

我想利用 Townscript 提供的 webhook 来更新模型中的 is_paid 字段。
数据的格式是(一个 json 字典):-链接(在服务器通知 API 列下)。
链接上的一条有用信息是:
我们将使用 post 参数data 以以下格式发送数据
这是python代码:

def payment(request):
    if request.method == "POST":
        posts=request.POST["data"]

        result=json.dumps(posts) #converting incoming json dict to string
        paymentemail(result)    # emailing myself the string (working fine)

        data = posts
        try:
            user = Profile.objects.filter(email=data['userEmailId']).first()
            user.is_paid = True
            user.save()
        except Exception as e: paymentemail(str(e))   # emailing myself the exception

        return redirect('/home')

    else:
        .......

与上述代码中的paymentemail()函数对应的两封电子邮件是:

"{\"customQuestion1\":\"+9175720*****\",\"customAnswer205634\":\"+917572******\",
    \"customQuestion2\":\"**** University\",\"customQuestion205636\":\"College Name\",\"ticketPrice\":**00.00,
    \"discountAmount\":0.00,\"uniqueOrderId\":\"***********\",\"userName\":\"********\",
    \"customQuestion205634\":\"Contact Number\",\"eventCode\":\"**********\",\"registrationTimestamp\":\"12-12-2019 22:22\",
        \"userEmailId\":\"***********@gmail.com\",etc....}"

我知道反斜杠用于转义引号。
第二封电子邮件:(这是个例外)

string indices must be integers

这是否意味着 data=request.POST['data'] 给了我一个字符串,从而在我使用 data['userEmailId'] 时导致错误?我该如何处理这个错误?

标签: pythonjsondjangodjango-formsdjango-views

解决方案


def payment(request):
    if request.method == "POST":
        posts=request.POST
        result=json.dumps(posts) #converting incoming json dict to string
        paymentemail(result)    # emailing myself the string (working fine)
        try:
            user = Profile.objects.filter(email=posts['userEmailId']).first()
            user.is_paid = True
            user.save()
        except Exception as e: paymentemail(str(e))   # emailing myself the exception

        return redirect('/home')

    else:
        .......

我改变了posts=request.POST["data"],因为它将只获得键“数据”的值,而不是我使用posts=request.POST这样我们将整个请求作为键值对(dict)。 user = Profile.objects.filter(email=posts['userEmailId']).first()


推荐阅读