python - 在 Google Cloud Function Python 中获取请求正文
问题描述
我正在尝试在 Python 中的 Google Cloud Functions 上设置 Stripe Webhooks。但是,我遇到了从函数获取请求正文的问题。请看看我的。下面的代码。
基本上我怎样才能得到request.body
?这是否以某种方式在 Cloud Functions 中提供?
import json
import os
import stripe
from django.http import HttpResponse
from django.views.decorators.csrf import csrf_exempt
stripe.api_key = 'XXXX'
# Using Django
@csrf_exempt
def my_webhook_view(request):
payload = request.body # This doesn't work!
event = None
print(payload)
try:
event = stripe.Event.construct_from(
json.loads(payload), stripe.api_key
)
except ValueError as e:
# Invalid payload
return HttpResponse(status=400)
# Handle the event
if event.type == 'payment_intent.succeeded':
payment_intent = event.data.object # contains a stripe.PaymentIntent
# Then define and call a method to handle the successful payment intent.
# handle_payment_intent_succeeded(payment_intent)
print(payment_intent)
elif event.type == 'payment_method.attached':
payment_method = event.data.object # contains a stripe.PaymentMethod
# Then define and call a method to handle the successful attachment of a PaymentMethod.
# handle_payment_method_attached(payment_method)
# ... handle other event types
print(payment_intent)
else:
print('Unhandled event type {}'.format(event.type))
return HttpResponse(status=200)
解决方案
该request
对象是 的一个实例flask.Request
。
根据您要对请求正文执行的操作,您可以调用request.args
、request.form
、request.files
、request.values
、request.json
,或者request.data
在请求正文尚未被解析的情况下调用。
推荐阅读
- c++ - Visual Studio 应用程序部署和外部库
- angular - 我似乎无法用 SplashScreen 和 StatusBar Ionic 6.12.4 找出这些错误
- symfony - 类中具有空值的唯一实体集 symfony / api-platform
- django - 来自 for 循环的 Django 模板渲染
- c# - 如何阻止我的 void Start 像一个 void 更新?
- python - python的什么命令清除文本文件中的文本?
- excel - 使用 Office 365 更新访问 Excel VBA 问题
- reactjs - 如何在单击 githubp 页面链接时获取 github 页面以打开特定页面
- node.js - 如何从 Node.js 内部的 postgreSQL 查询中返回一个数字
- python-3.x - 解析 Django 表单函数时出现意外的 EOF