Flask—静态资源配置

版权声明:此博客出自HuQi,感谢您的转载 https://blog.csdn.net/JSYhq/article/details/88619573

一、Flask实例化配置

1. 介绍

# 可对实例、配置模板文件路径、静态文路径进行配置
Flask(__name__, static_folder='mystatic', static_url_path='/myurl',template_folder='mytemplate')

# 静态文件目录的路径 默认当前项目中的static目录
static_folder = 'static'

# 静态文件目录的url路径 默认不写是与static_folder同名,远程静态文件时复用
static_url_path = None, 
 
# template模板目录, 默认当前项目中的 templates 目录
template_folder = 'templates'  

2. 实例讲解

# 默认Flask目录结构
/app.py
/static
    /js
    /css
    /img
/templates
    /index.html
# 前端访问后台静态资源,是通过/static/file.name
<link as=style href=/static/css/app.697eaad8.css rel=preload>
<img src="/static/img/mylogo.jpg" />

# 但有些前端应用中,资源文件必须要使用根路径/
<link rel=manifest href=/manifest.json>


那如何让Flask访问到这些根路径文件呢?
解决:配置一下 static_url_path、static_folder
(1)static_url_path:前端访问资源文件的前缀目录。默认是/static,就是前端必须这样访问
<img src="/static/img/mylogo.jpg" /> 我们改成 '',就可以这样访问了:
<img src="/img/mylogo.jpg" />。就达到前端从根目录访问的目的了。
(2)static_folder: 后端存储资源文件的目录。默认是/static,就是指明你后端的资源文件,
是放在<your project>/static/目录下,一般不需要改动。

猜你喜欢

转载自blog.csdn.net/JSYhq/article/details/88619573