如何動態配置靜態文件夾 staticcss
###問題 默認的Flask項目文件結構是這樣的:html
/app.py
/static
/js
/css
/img
/templates
/index.html
複製代碼
而後,你的前端訪問後臺靜態資源,是經過這個/static/file.name
url:前端
<link as=style href=/static/css/app.697eaad8.css rel=preload>
<img src="/static/img/mylogo.jpg" />
複製代碼
問題來了,在有些前端應用中,資源文件必需要使用根路徑/
! 好比PWA的manifest文件:vue
<link rel=manifest href=/manifest.json>
複製代碼
如何讓Flask訪問到這些根路徑的文件呢?git
###解決 文檔:http://flask.pocoo.org/docs/1.0/api/#configuration class flask.Flask(import_name, static_url_path=None, static_folder='static', static_host=None, host_matching=False, subdomain_matching=False, template_folder='templates', instance_path=None, instance_relative_config=False, root_path=None)github
配置一下static_url_path
、static_folder
就能夠了。json
/static
,就是前端必須這樣訪問:<img src="/static/img/mylogo.jpg" />
咱們改爲 '',就能夠這樣訪問了:<img src="/img/mylogo.jpg" />
。就達到前端從根目錄訪問的目的了。/static
,就是指明你後端的資源文件,是放在<your project>/static/
目錄下,通常不須要改動。###一個粟子:flask
from flask import Flask, render_template
app = Flask(__name__, static_url_path='')
@app.route('/')
def index():
return render_template('index.html')
複製代碼
源碼:https://github.com/kevinqqnj/flask-vue-pwa PWA演示:https://flask-vue-pwa.herokuapp.com/後端