【问题标题】:Return File/Stream response from googlevideo in Fast API从 Fastapi 中的谷歌视频返回文件/流响应
【发布时间】:2022-08-10 09:18:08
【问题描述】:

我正在使用 Fast API 从 googlevideo.com 返回视频响应。这是我正在使用的代码:

@app.get(params.api_video_route)
async def get_api_video(url=None):

  def iter():
     req = urllib.request.Request(url)

     with urllib.request.urlopen(req) as resp:
         yield from io.BytesIO(resp.read())


  return StreamingResponse(iter(), media_type=\"video/mp4\")

但这不起作用

我希望将此 Nodejs 转换为 python FAST API:

app.get(\"/download-video\", function(req, res) { 
 http.get(decodeURIComponent(req.query.url), function(response) { 
   res.setHeader(\"Content-Length\", response.headers[\"content-length\"]); 
   if (response.statusCode >= 400)         
     res.status(500).send(\"Error\");                     
     response.on(\"data\", function(chunk) { res.write(chunk); }); 
     response.on(\"end\", function() { res.end(); }); }); });
  • 什么不工作?你期望会发生什么?您收到任何错误消息吗?你得到了什么样的回应?如果您在调试器中观看该请求是否会返回任何数据(甚至是print 响应?)
  • @MatsLindh 它没有返回任何响应,API 一直在加载
  • app.get(\"/download-video\", function(req, res) { http.get(decodeURIComponent(req.query.url), function(response) { res.setHeader(\"Content-Length\", response.headers[\"content-length\"]); if (response.statusCode >= 400) res.status(500).send(\"Error\"); response.on(\"data\", 函数(chunk) { res.write(chunk); }); response.on(\"end\", function() { res.end(); }); }); });这是我在 python fastapi 中转换的 nodejs 代码
  • 您是否检查过您对resp.read() 的调用是否获得任何数据?它会被调用吗? urlopen 成功了吗?
  • @MatsLindh 是的,它正在返回字节,但我想要 mp4/video 格式,这需要很多时间

标签: python video-streaming urllib fastapi streamingresponsebody


【解决方案1】:

请改用以下内容,如文档 here 中所述。

#yield from io.BytesIO(resp.read())
yield from resp

【讨论】:

    【解决方案2】:

    我遇到了类似的问题,但都解决了。主要思想是使用requests.Session()创建一个会话,并一个一个地产生一个块,而不是获取所有内容并一次产生它。这非常有效,根本不会产生任何内存问题。

    @app.get(params.api_video_route)
    async def get_api_video(url=None):
    
      def iter():
         session = requests.Session()
         r = session.get(url, stream=True)
         r.raise_for_status()
         
         for chunk in r.iter_content(1024*1024):
             yield chunk
    
      return StreamingResponse(iter(), media_type="video/mp4") 
    
    

    【讨论】:

      猜你喜欢
      • 2018-11-11
      • 1970-01-01
      • 2014-08-02
      • 2021-12-05
      • 1970-01-01
      • 1970-01-01
      • 2020-07-24
      • 1970-01-01
      • 2018-11-15
      相关资源
      最近更新 更多