如何在Azure函数中接收多部分表单数据?

2024-04-28 05:40:42 发布

您现在位置:Python中文网/ 问答频道 /正文

我想在Azure函数中接收包含图像和文本的多部分数据

我可以在C#和nodeNode link中看到很多示例,但在python中找不到任何示例

在官方文件中也找不到任何内容Docs


Tags: 文件数据函数图像文本示例docs内容
1条回答
网友
1楼 · 发布于 2024-04-28 05:40:42

我已经尝试了以下代码,它对我有效:

import logging
import json
import io
from PIL import Image
from azure.storage.blob import BlobServiceClient,BlobClient
import azure.functions as func


def main(req: func.HttpRequest) -> func.HttpResponse:
    logging.info('Python HTTP trigger function processed a request.')

    name = req.form['name']
    interests =json.dumps(req.form["interests"], indent=2)
    imagefile = req.files["file"]
    filename = imagefile.filename
    filestream = imagefile.stream
    filestream.seek(0)

    blob = BlobClient.from_connection_string(conn_str= "<your connection string>", container_name="<container name>", blob_name="<blob name>")

    blob.upload_blob(filestream.read(), blob_type="BlockBlob")

    if name:
        return func.HttpResponse(f"Hello, {name}. Created profile with your interests : {interests}. Uploaded your profile image file :{filename} to the blob. This function executed successfully.")
    else:
        return func.HttpResponse(
             "This HTTP triggered function executed successfully. Pass a name in the query string or in the request body for a personalized response.",
             status_code=200
        )

但是,在这种情况下,您也可以使用PIL从映像中获取字节。然后代码看起来像:


import logging
import json
import io
from PIL import Image
from azure.storage.blob import BlobServiceClient,BlobClient
import azure.functions as func


def main(req: func.HttpRequest) -> func.HttpResponse:
    logging.info('Python HTTP trigger function processed a request.')

    name = req.form['name']
    interests =json.dumps(req.form["interests"], indent=2)
    filename = req.files["file"].filename
    image = Image.open(req.files["file"])
    imgByteIO = io.BytesIO()
    image.save(imgByteIO, format=image.format)
    imgByteArr = imgByteIO.getvalue()

    blob = BlobClient.from_connection_string(conn_str= "<your connection string>", container_name="<container name>", blob_name="<blob name>")
    blob.upload_blob(imgByteArr)

    if name:
        return func.HttpResponse(f"Hello, {name}. Created profile with your interests : {interests}. Uploaded your profile image file :{filename} to the blob. This function executed successfully.")
    else:
        return func.HttpResponse(
             "This HTTP triggered function executed successfully. Pass a name in the query string or in the request body for a personalized response.",
             status_code=200
        )


这是邮递员的要求:

Here is the postman request

相关问题 更多 >