Flask 未检测到“static”文件夹中的 CSS 文件

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

我一直在尝试运行 Flask 程序,但是它没有检测到静态文件夹中的 style.css 文件。我的不同目录的组织如下图所示:

file directories

我的app.py代码是:

from flask import Flask, render_template, request
import os
import joblib

template_dir = os.path.abspath('../templates')
app = Flask(__name__, template_folder=template_dir, static_folder='static')

我的index.html 文件包含:

<!-- templates/index.html -->
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <link rel="stylesheet" type="text/css" href="{{ url_for('static', filename='styles/style.css') }}">
    <title>App Title</title>
</head>

我尝试了不同的变体来让我的 Flask 应用程序识别我的 CSS 文件,但是没有一个起作用。我在网上遇到并尝试过的方法之一是添加:

app.static_url_path = '/static'
到我的 app.py 文件,但它仍然会导致错误。更具体地说,这是我的终端响应:

 * Debug mode: on
WARNING: This is a development server. Do not use it in a production deployment. Use a production WSGI server instead.
 * Running on http://127.0.0.1:5000
Press CTRL+C to quit
 * Restarting with stat
 * Debugger is active!
 * Debugger PIN: 652-831-486
127.0.0.1 - - [16/Dec/2023 13:23:07] "GET / HTTP/1.1" 200 -
127.0.0.1 - - [16/Dec/2023 13:23:07] "GET /static/styles/style.css HTTP/1.1" 404 -

如果有人有任何见解,我将非常感激。

css flask static-linking
1个回答
0
投票

刚刚想通了。对于任何可能遇到同样问题的人,我将 app.py 中的代码修改为:

template_dir = os.path.abspath('../templates')
static_dir = os.path.abspath('../static')
app = Flask(__name__, template_folder=template_dir, static_folder=static_dir)
© www.soinside.com 2019 - 2024. All rights reserved.