简体   繁体   中英

Returning a generator in Azure Function

Is it possible to return a generator in an Azure Function? 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 . Is it possible to do something like this in an Azure Function? I don't necessarily require it to be in Python, but it would be preferred.

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

If you want to return the number in the generator suppose you could return the 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.

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.

在此处输入图片说明

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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