【问题标题】:Returning a generator in Azure Function在 Azure Function 中返回生成器
【发布时间】:2020-04-13 09:55:34
【问题描述】:

是否可以在 Azure 函数中返回生成器?我正在尝试在创建数据时流式传输数据。我尝试了以下方法,但没有成功:

def main(req: func.HttpRequest) -> func.HttpResponse:
    def gen():
        for i in range(10):
            yield i

    return func.HttpResponse(gen(), mimetype='text/html')

以上产生TypeError: reponse is expected to be either of str, bytes, or bytearray, got generator。是否可以在 Azure 函数中执行类似的操作?我不一定要求它使用 Python,但它会是首选。

【问题讨论】:

    标签: python azure stream azure-functions


    【解决方案1】:

    我想这应该是可能的,可以看看这个example,你可能需要将响应转换为对象/字典。

    【讨论】:

      【解决方案2】:

      如果你想返回生成器中的数字,假设你可以返回list(gen())。如下图所示。

      我返回return func.HttpResponse(str(list(gen())),status_code=200),希望这是您想要的,如果您还有其他问题,请随时告诉我。

      如果您的目的是使用烧瓶返回生成器,您可以参考以下代码。

      import logging
      
      import azure.functions as func
      import json, os
      
      from flask import stream_with_context, request, Response
      from flask.app import Flask
      
      app = Flask(__name__)
      
      @app.route('/')
      def hello_world():
          def generate():
              yield 'Hello '
              yield 'world11'
          return Response(stream_with_context(generate()))
      
      def main(req: func.HttpRequest) -> func.HttpResponse:
          logging.info('Python HTTP trigger function processed a request.')
          uri=req.params['uri']
          with app.test_client() as c:
              doAction = {
                  "GET": c.get(uri).data,
                  "POST": c.post(uri).data
              }
              resp = doAction.get(req.method).decode()
              return func.HttpResponse(resp, mimetype='text/html')
      

      这是测试结果图片。

      【讨论】:

      • 我希望流式传输文件以避免在内存中携带大文件。流式传输的优点是您一次只能在内存中存储一​​个块。我的原始代码只是一个玩具示例,实际上我正在寻找流式传输视频文件供客户端下载。视频文件将即时生成和流式传输。 Flask 对此有一个完美的功能,称为“stream_with_context”,但我无法成功实现它。这是文档flask.palletsprojects.com/en/1.1.x/api/…
      • 执行 str(list(gen())) 将创建输出文件然后发送它。但我希望在 gen() 运行时流式传输它(类似于烧瓶 stream_with_context)
      • 这确实成功地提供了文件;但是,它在返回响应之前完全完成了 gen() 函数。所以整个响应都保存在内存中,这是我试图避免的。
      猜你喜欢
      • 1970-01-01
      • 2018-09-30
      • 1970-01-01
      • 1970-01-01
      • 2020-09-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多