python - Azure Functions 如何在脚本完成之前返回 HttpResponse 或显示消息

标签 python azure azure-functions

我有一个 Python Azure 函数,它由一个文件和一个 main 函数组成:

def main(req: func.HttpRequest) -> func.HttpResponse:
    [bunch of code]

    return func.HttpResponse("the file will be deleted in 10 minutes", status_code=200)

它会在 Azure Blob 存储中为用户创建一个文件,并在 10 分钟内将其删除。我使用 time.sleep(600) 来执行此操作。但是,该消息仅在该计时器结束时(文件已被删除后)到达。

如何让 HttpResponse 在脚本结束之前显示消息,然后等待 10 分钟再删除消息?

我尝试在 time.sleep(600) 之前添加 func.HttpResponse('the file will be deleted in 10 分钟') 但没有成功返回任何内容。

最佳答案

对于像这样具有 http 输出绑定(bind)的函数,您必须在末尾返回 http 响应才能使响应正常工作。因此,使用单个函数是无法实现这一目标的。继续阅读替代解决方案。

这个问题通常是一个“异步”处理示例,您希望立即响应“好吧,我要这样做”,同时它“排队进一步处理”以便在后端继续。要在 Azure Function 中实现此目的,您将需要以下 2 个函数:

  1. 功能 1:Http trigger, http outputQueue output binding (为了简单起见,我将使用存储队列)。
  2. 功能 2:Queue trigger (将由函数 1 排队的消息触发)。

功能1(根据您的需要更新):

JSON:

{
  "scriptFile": "__init__.py",
  "bindings": [
    {
      "authLevel": "function",
      "type": "httpTrigger",
      "direction": "in",
      "name": "req",
      "methods": [
        "get",
        "post"
      ]
    },
    {
      "type": "http",
      "direction": "out",
      "name": "$return"
    },
    {
      "type": "queue",
      "direction": "out",
      "name": "msg",
      "queueName": "outqueue",
      "connection": "AzureStorageQueuesConnectionString"
    }
  ]
}

代码:

import azure.functions as func

def main(req: func.HttpRequest, msg: func.Out[str]) -> func.HttpResponse:
    [bunch of code]
    input_msg = "<create the message body required by function 2>"
    msg.set(input_msg)
    return func.HttpResponse("the file will be deleted in 10 minutes", status_code=201)

功能2(根据您的需要更新):

JSON:

{
  "scriptFile": "__init__.py",
  "bindings": [
    {
      "name": "msg",
      "type": "queueTrigger",
      "direction": "in",
      "queueName": "messages",
      "connection": "AzureStorageQueuesConnectionString"
    }
  ]
}

代码:

import json
import azure.functions as func

def main(msg: func.QueueMessage):  
     # below is just an example of parsing the message, in your case it might be taking the blob info required for deleting
     message = json.dumps({
        'id': msg.id,
        'body': msg.get_body().decode('utf-8'),
        'expiration_time': (msg.expiration_time.isoformat()
                            if msg.expiration_time else None),
        'insertion_time': (msg.insertion_time.isoformat()
                           if msg.insertion_time else None),
        'time_next_visible': (msg.time_next_visible.isoformat()
                              if msg.time_next_visible else None),
        'pop_receipt': msg.pop_receipt,
        'dequeue_count': msg.dequeue_count
    })

    [bunch of code]

注意:您还可以查看 Durable Functions您可以在其中处理复杂的工作流程,而无需自己管理排队。但由于您在本例中的场景非常简单,所以我没有介绍它。

关于python - Azure Functions 如何在脚本完成之前返回 HttpResponse 或显示消息,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64027825/

相关文章:

python - sql python 上查询字符串的 WHERE 动态绑定(bind)

postgresql - 尝试从 Azure Postgres 数据库备份时 pg_dump 失败错误 : query would be affected by row-level security policy for table "job"

azure - 使用MySQL In App数据库的azure应用程序服务使用的phpmyadmin安装文件夹在哪里?

python - 检查 *some* 用户是否存在于 Linux 或 Windows 中的可移植方法?

python - 识别 spaCY 中的 "it"主题

python - 类(class)员工打印方式

python - 重命名azure blob存储中的spark输出csv

Azure 函数不由 blob 事件触发

azure - 是否可以将 .net core Web api 发布到 azure 函数?

azure - 来自 Azure Function 的 TcpIp 通信?