且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

Flask在Python中找不到文件夹和文件

更新时间:2023-11-19 20:33:16

Flask会在您的项目根目录的以下目录中自动查找CSS,JS和其他静态文件:

 /static 

Flask文档中的更多详细信息,此处.>

优良作法是将静态文件分成子目录,如下所示:

 /static/css/静态/js 

在您的示例中,将CSS放在以下路径:

 /static/css/style.css 

然后在您的HTML中进行引用:

 < link rel ="stylesheet" href ="/static/css/style.css"> 

如果您使用的是Jinja2模板,则可以按照文档中的说明进行操作:

  {{url_for('static',filename ='style.css')}} 

My files structure is following

> code.py

> templates

....> css

....> index.html

and my flask code is

from flask import Flask, url_for
from flask import render_template

app = Flask(__name__)

@app.route('/')
def index():
    return render_template('index.html')

if __name__ == "__main__":
    app.run()

and my HTML code is

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Title</title>
    <link rel="stylesheet" href="/css/style.css">
</head>
<body>
    <header>
        <img class="resize" src="./pictures/apptek_logo.png" alt="apptek_logo">
        <nav>
            <ul class="nav-links">
                <li class="active"><a href="./index.html">Home</a></li>
                <li><a href="./contact.html">Contact</a></li>
            </ul>
            <script src="https://code.jquery.com/jquery-3.5.0.js"></script>
            <script type="text/javascript">
                $(document).on('click', 'ul li', function(){
                    $(this).addClass('active').siblings().removeClass('active')
                })
            </script>
        </nav>
    </header>
</body>
</html>

For some reason, it's not loading CSS files, and any other html files at all. Is there anything necessary in Flask I have to do?

Flask automatically looks for CSS, JS and other static files in your project root, in the directory:

/static

More details in the Flask docs here.

It's good practice to seperate your static files into subdirectories, like so:

/static/css
/static/js

In your example, place your CSS at the path:

/static/css/style.css

Then reference as so in your HTML:

<link rel="stylesheet" href="/static/css/style.css">

If you're using Jinja2 templates, you can do as described in the documentation:

{{ url_for('static', filename='style.css') }}