在Azure Function中返回生成器

时间:2019-12-21 01:07:51

标签: python azure stream azure-functions

是否可以在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中,但是它是首选。

2 个答案:

答案 0 :(得分:0)

我想这应该可行,请看一下example,您可能需要将响应转换为对象/字典。

答案 1 :(得分:0)

如果要返回生成器中的数字,则可以返回list(gen())。它将像下面的图片一样。

enter image description here

我退回了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')

这是测试结果图片。

enter image description here