简体   繁体   English

在 Azure 函数中返回生成器

[英]Returning a generator in Azure Function

Is it possible to return a generator in an Azure Function?是否可以在 Azure 函数中返回生成器? I am trying to stream data while it is being created.我正在尝试在创建数据流式传输数据。 I tried the following with no luck:我尝试了以下但没有运气:

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

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

The above yielded TypeError: reponse is expected to be either of str, bytes, or bytearray, got generator .上面产生的TypeError: reponse is expected to be either of str, bytes, or bytearray, got generator Is it possible to do something like this in an Azure Function?是否可以在 Azure 函数中执行此类操作? I don't necessarily require it to be in Python, but it would be preferred.我不一定要求它在 Python 中,但它会是首选。

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

If you want to return the number in the generator suppose you could return the list(gen()) .如果您想返回生成器中的数字,假设您可以返回list(gen()) It will act like the below pic.它会像下图一样。

在此处输入图片说明

I return the return func.HttpResponse(str(list(gen())),status_code=200) , hope this is what you want, if you still have other problem please feel free to let me know.我返回return func.HttpResponse(str(list(gen())),status_code=200) ,希望这是你想要的,如果你还有其他问题,请随时告诉我。

If your purpose is use flask to return a generator you could refer to the below code.如果您的目的是使用烧瓶返回生成器,您可以参考以下代码。

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')

Here is the test result pic.这是测试结果图片。

在此处输入图片说明

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM