教程:提供视频#
在本教程中,我们将构建一个非常基本的视频服务器。它将直接提供视频。
本教程旨在作为在 Quart 中使用条件响应提供大型文件的入门。如果您想跳到最后,代码在 Github 上。
1:创建项目#
我们需要为我们的视频服务器创建一个项目,我喜欢使用 Poetry 来完成此操作。Poetry 通过 pip(或通过 Brew)安装。
pip install poetry
然后我们可以使用 Poetry 创建一个新的视频项目
poetry new --src video
现在可以在 video 目录中开发我们的项目,所有后续命令都应该在 video 目录中运行。
2:添加依赖项#
我们只需要 Quart 来构建这个简单的视频服务器,我们可以通过运行以下命令将其安装为项目的依赖项
poetry add quart
Poetry 会通过运行以下命令来确保此依赖项存在并且路径正确
poetry install
3:创建应用程序#
我们需要一个 Quart 应用程序作为我们的 Web 服务器,它由以下添加到 src/video/__init__.py 中的内容创建
from quart import Quart
app = Quart(__name__)
def run() -> None:
app.run()
为了方便运行应用程序,我们可以从诗歌脚本调用 run 方法,通过将以下内容添加到 pyproject.toml 中
[tool.poetry.scripts]
start = "video:run"
这允许以下命令启动应用程序
poetry run start
4:提供 UI#
当用户访问我们的网站时,我们会直接向他们显示同一个视频,以及通过块的方式显示。以下 HTML 模板应添加到 src/video/templates/index.html 中
<video controls width="100%">
<source src="/video.mp4" type="video/mp4">
</video>
就样式而言,这是一个非常基本的 UI。
现在,我们可以为根路径(即 /
)提供此模板,方法是将以下内容添加到 src/video/__init__.py 中
from quart import render_template
@app.get("/")
async def index():
return await render_template("index.html")
5:实现路由#
由于我们正在提供大型文件,因此我们应该允许使用条件响应。这是响应中返回的数据取决于请求内容的地方。这是通过 Range
头字段完成的,可以通过 request.range
属性进行检查。
Quart 具有内置方法来使响应以请求范围为条件。第一个是在发送文件时使用条件参数,第二个是使用响应 make_conditional
方法。前者显示在下面,应添加到 src/video/__init__.py 中
@app.route("/video.mp4")
async def auto_video():
return await send_file(app.static_folder / "video.mp4", conditional=True)
6:测试#
要测试我们的应用程序,我们需要检查除非发出条件范围请求,否则是否返回了完整视频。这是通过将以下内容添加到 tests/test_video.py 中来完成的
from video import app
async def test_auto_video() -> None:
test_client = app.test_client()
response = await test_client.get("/video.mp4")
data = await response.get_data()
assert len(data) == 255_849
response = await test_client.get("/video.mp4", headers={"Range": "bytes=200-1000"})
data = await response.get_data()
assert len(data) == 801
由于测试是一个异步函数,因此我们需要安装 pytest-asyncio,方法是运行以下命令
poetry add --dev pytest-asyncio
安装完成后,需要通过将以下内容添加到 pyproject.toml 中来配置它
[tool.pytest.ini_options]
asyncio_mode = "auto"
最后,我们可以通过以下命令运行测试
poetry run pytest tests/
如果您在 Quart 示例文件夹中运行此命令,则需要添加 -c pyproject.toml
选项以防止 pytest 使用 Quart pytest 配置。
7:总结#
我们构建了一个服务器,该服务器将根据客户端的请求以条件方式提供大型文件,包括限制最大部分大小的功能。