从POST请求中提取json dict

2024-09-27 00:17:41 发布

您现在位置:Python中文网/ 问答频道 /正文

我想利用Townscript提供的webhook来更新我的模型中的is\u paid字段。
数据的格式是(json dict):-link(在服务器通知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']时出错?如何处理此错误


Tags: 代码jsondatastringisrequest格式result
1条回答
网友
1楼 · 发布于 2024-09-27 00:17:41
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"],因为将只获取键“data”的值,因此我使用posts=request.POST,以便将整个请求作为键-值对(dict)获取。 user = Profile.objects.filter(email=posts['userEmailId']).first()

相关问题 更多 >

    热门问题