Flask静态文件访问添加路径

Flask静态文件访问添加路径

Flask静态文件访问添加路径

在使用Flask构建Web应用程序时,我们经常需要处理静态资源文件,如JavaScript、CSS和图片等。Flask默认会在项目根目录下建立一个名为static的静态文件夹,用于存放这些静态资源文件。但有时候我们希望将静态文件存放在其他目录下,并且希望通过不同的URL访问这些静态文件。本文将详细介绍如何在Flask应用程序中添加路径来访问静态文件。

静态文件路径设置

在Flask应用程序中,我们可以通过static_folderstatic_url_path参数来设置静态文件的路径和访问URL。

from flask import Flask

app = Flask(__name__, static_folder='path/to/static/files', static_url_path='/custom/static')

@app.route('/')
def index():
    return 'Hello, Flask!'

上面的代码中,我们在创建Flask应用程序时指定了static_folder参数,将静态文件存放在path/to/static/files目录下,并通过static_url_path参数设置了访问静态文件的URL为/custom/static

静态文件访问

当我们需要在模板或者页面中引用静态资源文件时,可以使用url_for('static', filename='path/to/file')函数来生成静态资源文件的URL。

from flask import Flask, render_template, url_for

app = Flask(__name__, static_folder='path/to/static/files', static_url_path='/custom/static')

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

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

if __name__ == '__main__':
    app.run()
<!-- index.html -->
<!DOCTYPE html>
<html>
<head>
    <title>Index</title>
    <link rel="stylesheet" href="{{ url_for('static', filename='css/style.css') }}">
</head>
<body>
    <h1>Welcome to Index Page</h1>
    <script src="{{ url_for('static', filename='js/script.js') }}"></script>
</body>
</html>

<!-- about.html -->
<!DOCTYPE html>
<html>
<head>
    <title>About</title>
    <link rel="stylesheet" href="{{ url_for('static', filename='css/style.css') }}">
</head>
<body>
    <h1>About Us</h1>
    <script src="{{ url_for('static', filename='js/script.js') }}"></script>
</body>
</html>

在上面的代码中,我们在模板中引用了css/style.cssjs/script.js这两个静态文件,使用url_for('static', filename='path/to/file')函数生成了静态文件的URL,生成的URL会自动加上指定的static_url_path

运行结果

假设我们有以下的目录结构:

- project
  - app.py
  - static
    - css
      - style.css
    - js
      - script.js
  - templates
    - index.html
    - about.html

style.cssscript.js文件中分别写入以下内容:

/* style.css */
body {
    background-color: lightblue;
    color: white;
}

/* script.js */
alert('Hello, World!');

index.htmlabout.html文件中分别写入以下内容:

<!DOCTYPE html>
<html>
<head>
    <title>Index</title>
    <link rel="stylesheet" href="{{ url_for('static', filename='css/style.css') }}">
</head>
<body>
    <h1>Welcome to Index Page</h1>
    <script src="{{ url_for('static', filename='js/script.js') }}"></script>
</body>
</html>

<!DOCTYPE html>
<html>
<head>
    <title>About</title>
    <link rel="stylesheet" href="{{ url_for('static', filename='css/style.css') }}">
</head>
<body>
    <h1>About Us</h1>
    <script src="{{ url_for('static', filename='js/script.js') }}"></script>
</body>
</html>

当我们访问http://127.0.0.1:5000/http://127.0.0.1:5000/about页面时,会看到页面中的背景颜色变为lightblue,并弹出一个提示框显示Hello, World!

结论

通过在Flask应用程序中设置静态文件的路径和访问URL,我们可以方便地管理和引用静态资源文件。使用url_for('static', filename='path/to/file')函数可以生成静态文件的URL,使得我们可以通过不同的路径访问静态文件。这样可以更好地组织和管理静态资源文件,提高Web应用程序的开发效率。

Python教程

Java教程

Web教程

数据库教程

图形图像教程

大数据教程

开发工具教程

计算机教程