Azure Function流式返回

最近用azure function做了一个api和llm交互,需要流式返回。但是默认不支持流返回,搜索了一下。记录。

官方文档:
https://techcommunity.microsoft.com/blog/azurecompute/azure-functions-support-for-http-streams-in-python-is-now-in-preview/4146697

根据文档需要以下步骤:

前置条件

  1. Azure Functions runtime version 4.34.1, or a later version.
  2. Python version 3.8, or a later supported version.
  3. Python v2 programming model

首先第一点,这个Azure Functions runtime version版本,可以在local.settings.json或者式环境变量里面设置,如果式本地 func start启动的话也需要加PYTHON_ENABLE_INIT_INDEXING这个变量设置为1,如果线上deploy的话就加到application setting里面。

python 复制代码
{
  "IsEncrypted": false,
  "Values": {
    "PYTHON_ENABLE_INIT_INDEXING": "1",
    "FUNCTIONS_WORKER_RUNTIME": "python",
    "AzureWebJobsStorage": "UseDevelopmentStorage=true",
    "FUNCTIONS_EXTENSION_VERSION":"4.34.1"
  }
}

Azure Functions runtime version这个使用的版本可以用 func start --verbose输出更多参数查看到

第二点python版本不需要多讲。第三点azure programming版本的话就在host.json查看。

python 复制代码
{
  "version": "2.0",
  "logging": {
    "applicationInsights": {
      "samplingSettings": {
        "isEnabled": true,
        "excludedTypes": "Request"
      }
    }
  },
  "extensionBundle": {
    "id": "Microsoft.Azure.Functions.ExtensionBundle",
    "version": "[4.*, 5.0.0)"
  }
}

引入新包

bash 复制代码
pip install azurefunctions-extensions-http-fastapi

编写代码

python 复制代码
from azurefunctions.extensions.http.fastapi import Request, StreamingResponse
python 复制代码
import time
import azure.functions as func
from azurefunctions.extensions.http.fastapi import Request, StreamingResponse

app = func.FunctionApp(http_auth_level=func.AuthLevel.ANONYMOUS)

def generate_count():
    """Generate a stream of chronological numbers."""
    count = 0
    while True:
        yield f"counting, {count}\n\n"
        count += 1

@app.route(route="stream", methods=[func.HttpMethod.GET])
async def stream_count(req: Request) -> StreamingResponse:
    """Endpoint to stream of chronological numbers."""
    try:
        req_body = await req.json()
        query = req_body.get('query')
        logging.info('stream_count get parm: {query}')
    except Exception:
        traceback.print_exc()
        return StreamingResponse(content='Request parm error need {"query":str} ',status_code=500, media_type="text/event-stream")

    return StreamingResponse(generate_count(), media_type="text/event-stream")

如果是非流返回的api就不能使用默认的func.HttpResponse作为返回了,需要使用JSONResponse

python 复制代码
from azurefunctions.extensions.http.fastapi import Request,JSONResponse
@app.route(route="all_u_need_create", methods=[func.HttpMethod.GET])
async def all_u_need_create(req: Request) -> JSONResponse:
    
    ...
    return JSONResponse(content=ids,status_code=200)
    

测试

这边有点奇怪的是,我使用postman测试一直显示不了返回的流,我一度以为我代码有问题,找了半天,结果用 curl测试没有任何问题.有知道怎么解决的同学也可以给我讲一下。

bash 复制代码
curl -X GET --data-raw '{"query":"xxxxx"}' -H "Content-Type: application/json" http://localhost:7071/api/all_u_need_search

所以之后的测试就一直用的curl测试了。

相关推荐
ChoSeitaku4 小时前
NO.3数据结构栈和队列|顺序栈|共享栈|链栈|顺序队|循环队列|链队|双端队列|括号匹配|中缀表达式转后缀|后缀表达式求值
数据结构·microsoft
LCG元8 小时前
MCP选型指南:AWS vs Azure vs GCP vs 国内云厂商深度对比
flask·azure·aws
干净的坏蛋9 小时前
Microsoft Word 中 .doc 和 .docx 的区别
microsoft·word
Leinwin19 小时前
微软智能语音平台赋能理想汽车:创新驱动,引领智能出行新体验
microsoft
杰哥技术分享1 天前
宝塔 php支持sqlserver
microsoft
Linux运维技术栈1 天前
企业级配置:Azure 邮件与 Cloudflare 域名解析的安全验证落地详解
运维·安全·flask·azure·cloudflare
阿酷tony1 天前
微软语音合成标记语言SSML文档结构和事件(详细文档和实例)
microsoft·微软语音·ssml文档结构·ssml结构·ssml语音合成
qb_jiajia2 天前
2025年微软mos备考攻略-穷鬼版
microsoft·微软
FreeBuf_2 天前
微软365 PDF导出功能存在本地文件包含漏洞,可泄露敏感服务器数据
服务器·microsoft·pdf
Leinwin2 天前
微软上线 Deep Research 预览版:o3+必应赋能研究自动化
运维·microsoft·自动化