Flask 静态文件服务问题:视频文件出现 404 错误

问题描述 投票:0回答:1

我在 Flask 应用程序中遇到静态文件问题,并且希望获得一些解决该问题的指导,因为我几乎没有 Web 开发经验。

如果我没有很好地解释事情,我深表歉意,但这里是问题的摘要:

问题: 当尝试在 Flask 网站上加载静态文件(mp4 视频)时,我始终收到 404 错误。尽管确保正确的文件路径和权限,但我无法解决问题,我意识到已经存在很多关于提供静态文件的问题,但提供的解决方案不起作用,而且情况有点不同,因为我只想添加我网站的背景视频。

这是我的 Flask 应用程序中的相关代码片段:

Flask 应用程序设置

app = Flask(__name__)
app._static_folder = '/static'

背景视频的 HTML/CSS

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Barcode Wall Control Server</title>
    <!-- Bootstrap CSS -->
    <link href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css" rel="stylesheet">
    <style>
        @media screen and (max-height: 450px) {
            .sidebar {padding-top: 15px;}
            .sidebar a {font-size: 18px;}
        }

        #mainContent {
        padding: 20px;
        }

        /*Video Background */
        #backVideo {
            position: fixed;
            right: 0;
            bottom: 0;
            min-width: 100%;
            min-height: 100%;
            width: auto;
            height: auto;
            z-index: -1;
            overflow: hidden;
        }

    </style>
</head>
<body style="background-color: #b8b7b74f;">

    <video autoplay loop muted id="backVideo">
        <source src="{{url_for('static', filename='barcode.mp4')}}" type="video/mp4">
    </video>
</body>  

尝试加载静态文件时,我的终端显示以下错误消息:

[15/May/2024 14:38:46] "GET /static/barcode.mp4 HTTP/1.1" 404

PS。当我在没有服务器的情况下直接运行 html 代码时,视频加载没有问题。

html css linux flask
1个回答
0
投票

我认为你这里有一些问题。你还没有指定你正在使用哪个版本的 Flask,但我不记得曾经见过使用

_static_folder
(即带有下划线前缀)指定静态路径的选项。

您应该能够使用 Flask 实例的

static_folder
属性或通过向 Flask 构造函数提供
static_folder=...
kwarg 来配置它。

另一个问题是路径应该是相对路径或绝对路径(例如 /static 在你的文件系统上),我假设你不想要——尽管它确实有效。从文档中,“相对于应用程序 root_path 或绝对路径。”

因此,您可能应该将代码更改为:

app = Flask(__name__, static_folder="static") 
# or 
# app.static_folder = "static"

还值得注意的是,

static
是默认值。因此,如果这不起作用,您可能需要确保静态文件夹根据应用程序的
root_path
正确定位。例如,

├── app
│   ├── __init__.py
│   ├── routes.py
│   └── *static*

在实例化 Flask 实例后尝试添加以下内容以确定不提供静态资源的原因:

print(app.root_path)
print(app.has_static_folder)
print(app.static_folder)
import os
names = os.listdir(os.path.join(app.static_folder))
print(names) # list of static files
© www.soinside.com 2019 - 2024. All rights reserved.