python - 从 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'] 时导致错误?我该如何处理这个错误?
解决方案
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()
推荐阅读
- amazon-web-services - 使用 build-spec.yml 中的环境变量构建 AWS 代码
- django - Django:如何制作编辑 JSON 文件而不是模型的自定义管理视图?
- javascript - ChartJS 时间轴未正确绘制 | 得到一个小时而不是日期
- python - PyQT5 与 matplotlib 图,事件循环已经在运行
- php - 带有计数器的php id并保存文件
- angular - 如何在角度/打字稿中声明变量
- html - 在 Chrome 中隐藏 HTML 时间输入字段上的图标
- date - Elasticsearch中日期数据类型的平均聚合?
- oracle - 触发器函数 - 每当在表“zaposlenici”中添加或更改某些内容时,创建一个设置列“inicijali”的触发器
- php - Composer 自定义 GitLab 服务器依赖项