【问题标题】:How to receive an image from a POST request on Google Cloud Function with Python?如何使用 Python 从 Google Cloud Function 上的 POST 请求中接收图像?
【发布时间】:2024-05-21 21:40:01
【问题描述】:

我正在努力重组通过 POST 请求发送到 GCP 云函数的图像。

我查看了 here 关于如何使用 POST 请求打包文件的建议。

我希望该函数能够从字节重建图像以进行进一步处理,每次我发送请求时都会返回“失败”。任何帮助将不胜感激!

### client_side.py
import requests

url = 'https://region-project.cloudfunctions.net/function' # Generic GCP functions URL
files = {'file': ('my_image.jpg', open('my_image.jpg', 'rb').read(), 'application/octet-stream')}
r = requests.post(url, files=files)

### gcp_function.py
from io import BytesIO

def handler(request):
    try:
        incoming = request.files.get('file')
        bytes = BytesIO(incoming)
        image = open_image(bytes)
        message = 'Success'
    except:
        message = 'Failure'
    return message

【问题讨论】:

  • 您会收到“失败”,因为这是您设置它返回的消息。尝试返回异常消息以获取更多有用信息。
  • @mgoya 非常感谢!明白了。

标签: python-3.x google-cloud-platform python-requests google-cloud-functions http-post


【解决方案1】:

排序。

需要读取方法将 FileStorage 对象转换为字节。

### gcp_function.py
from io import BytesIO
import logging

def handler(request):
    try:
        incoming = request.files['file'].read()
        bytes = BytesIO(incoming)
        image = open_image(bytes)
        message = 'Success'
    except Exception as e:
        message = 'Failure'
        logging.critical(str(e))
    return message

【讨论】: