【发布时间】:2020-04-06 04:54:05
【问题描述】:
我想利用 Townscript 提供的 webhook 来更新我模型中的 is_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'] 时导致错误?我该如何处理这个错误?
【问题讨论】:
-
可能
request.POST["data"]是一个字符串,而您将其分配给data,而当您尝试data['userEmailId']时,它会抛出错误。尝试删除该尝试除外,以便您可以查明错误。 -
@NalinDobhal python 应用程序部署在 heroku 上,这个特定功能仅在有人注册事件时运行。所以,我想给自己发电子邮件异常是知道发生了什么样的错误的方法之一。如果我正确删除了 try 和 except 语句,因为应用程序已部署并且我无法在本地服务器上对其进行测试,因此我将无法使用它。据我所知 request.POST['data'] 应该返回一个 json 字典,如 townscript 网站上所述,但当然通过使用 request.POST['data'] 我没有得到我想要的。如果数据变成了字符串,我该怎么办?
-
检查数据是json还是string。如这里所示,数据是字符串,您可以使用 python
json包
标签: python json django django-forms django-views