python - FASTAPI:无法呈现 html 页面
问题描述
我正在尝试渲染显示来自网络摄像头的视频捕获的 html 页面。但面临错误: - 500 Server Error TypeError: TemplateResponse() missing 1 required positional argument: 'context'
。我在 Flask 中尝试过的相同代码,它在那里工作正常。
from fastapi import FastAPI
import uvicorn
from fastapi import Depends, FastAPI
from fastapi import FastAPI, Request
from fastapi.responses import HTMLResponse
from fastapi.templating import Jinja2Templates
import cv2
app = FastAPI(debug=True)
templates = Jinja2Templates(directory="templates")
@app.get("/")
async def index():
return templates.TemplateResponse("index.html")
async def gen_frames(camera_id):
cap= cv2.VideoCapture(0)
while True:
# for cap in caps:
# # Capture frame-by-frame
success, frame = cap.read() # read the camera frame
if not success:
break
else:
ret, buffer = cv2.imencode('.jpg', frame)
frame = buffer.tobytes()
yield (b'--frame\r\n'b'Content-Type: image/jpeg\r\n\r\n' + frame + b'\r\n')
if __name__ == '__main__':
uvicorn.run(app, host="127.0.0.1",port=8000)
我的 HTML 页面是:- index.html
<!doctype html>
<html lang="en">
<head>
<!-- Required meta tags -->
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<!-- Bootstrap CSS -->
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css"
integrity="sha384-MCw98/SFnGE8fJT3GXwEOngsV7Zt27NXFoaoApmYm81iuXoPkFOJwJ8ERdknLPMO" crossorigin="anonymous">
<title>Multiple Live Streaming</title>
</head>
<body>
<div class="container">
<div class="row">
<div class="col-lg-7">
<h3 class="mt-5">Multiple Live Streaming</h3>
<img src="{{ url_for('video_feed', id='0') }}" width="100%">
</div>
</div>
</div>
</body>
</html>
任何人都可以帮忙。我在这做错了什么。?相同的代码在 Flask 中工作
解决方案
使用模板时需要传递请求。
from fastapi import Request
@app.get("/")
async def index(request: Request):
return templates.TemplateResponse("index.html", {"request": request})
因此,您还可以使用StreamingResponse将视频作为另一条路径提供
from fastapi.responses import StreamingResponse
@app.get("/serve/{camera_id}", include_in_schema=False)
async def serve_video(camera_id: int):
return StreamingResponse(gen_frames(camera_id))
然后使用 Ajax 或 Axios 等获取该响应。
推荐阅读
- oracle - 使用 Jdeveloper 12 在 XSLT 转换中添加高级函数 ora:getFaultAsString()
- go - Go 模块作为 go1.10 的依赖管理器?
- numerical-integration - C++ 中未指定参数的数值积分
- javascript - 在本机反应中将外部文件连接到 App.js 时出现问题
- gradle - Gradle Artifactory 插件应该使用纯文本还是加密密码?
- matlab - FFT后幅度错误[Matlab]
- django - 如何修复 NoReverseMatch Django 错误?
- microsoft-teams - Teams 中自定义选项卡的设置
- swiftui - SwiftUI 没有隐藏动画
- php - 如何使用 laravel 以相同的顺序从 mysql 获取?