• FastAPI(51)- 自定义响应之 StreamingResponse、FileResponse


    更多自定义响应类型

    StreamingResponse

    作用

    采用异步生成器或普通生成器(generator)/迭代器(iterator)流式传输响应数据

    实际代码

    from fastapi import FastAPI
    from fastapi.responses import StreamingResponse
    
    file_path = "test.mp4"
    app = FastAPI()
    @app.get("/")
    def main():
        # 这是生成器函数。它是一个“生成器函数”,因为它里面包含了 yield 语句
        def iterfile():
            # 通过使用 with 块,确保在生成器函数完成后关闭类文件对象
            with open(file_path, "rb") as file_like:
                # yield from 告诉函数迭代名为 file_like 的东西
                # 对于迭代的每个部分,yield 的内容作为来自这个生成器函数
                yield from file_like
    
        return StreamingResponse(iterfile(), media_type="video/mp4")
    • 如果有一个类文件对象(例如 open() 返回的对象),可以创建一个生成器函数来迭代该类文件对象
    • 这样,不必首先在内存中读取所有内容,可以将该生成器函数传递给 StreamingResponse,然后返回它
    • 这包括许多与云存储、视频处理等交互的库

    请求结果

    返回了视频啦!

    源码 

     

    FileResponse

    作用

    异步流式传输文件作为响应,重点一定是异步的

    实际代码

    from fastapi import FastAPI
    from fastapi.responses import FileResponse
    
    file_path = "test.mp4"
    app = FastAPI()
    
    
    @app.get("/file", response_class=FileResponse)
    async def main():
        return file_path

    感觉这个比 StreamimgResponse 简单多了

    请求结果

    和上面 StreamingResponse 一样,也返回了视频啦!

    源码

     

  • 相关阅读:
    html5新增元素和废除元素
    html5本地存储
    第四章表单与文件笔记新增属性
    第五章canvas
    lable中for的作用
    第四章表单与文件学习内容
    第三章html5的结构
    html5的全局属性
    正则表达式—升华
    微前端
  • 原文地址:https://www.cnblogs.com/poloyy/p/15365104.html
Copyright © 2020-2023  润新知