【问题标题】:Getting Request Body in Google Cloud Function Python在 Google Cloud Function Python 中获取请求正文
【发布时间】:2021-01-25 03:28:56
【问题描述】:

我正在尝试使用 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 对象将不包含完整的有效负载如果其内容无法解析。见this。 request.body 是一个 nodejs 构造,在 python/Flask 中不可用。
  • 答案取决于您如何 POST 或 PUT 数据和 mimetype。这个答案可能会有所帮助:stackoverflow.com/a/16664376/8016720
  • 你如何调用你的函数?你可以试试request.get_data()吗?

标签: python google-cloud-platform google-cloud-functions stripe-payments


【解决方案1】:

request 对象是flask.Request 的一个实例。

根据您要对请求正文执行的操作,您可以调用 request.argsrequest.formrequest.filesrequest.valuesrequest.jsonrequest.data,如果请求正文没有'没有被解析。

【讨论】:

    猜你喜欢
    • 2017-08-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-12-06
    • 2019-02-25
    • 2018-06-17
    • 2021-10-29
    相关资源
    最近更新 更多