2016-02-24 56 views
2

我的問題與本網站上的其他幾個相似,但我在那裏找到的答案並不適合我。燒瓶未在我的軟件包的「靜態」目錄中找到文件

我正在學習燒瓶。我在使用Vagrant VM的Ubuntu 10.04機器上運行Flask 0.10.1和Python 2.7。

我已經嘗試過無數次SO,Flask文檔和Miguel Grinberg的建議,但都沒有成功。

因此,我展示了最簡單的版本,我認爲可能工作(但不是)爲您的細讀。

註釋掉的替代行(在page_a.html和page_b.html中)工作但是很可怕。

首先,這裏是我的項目的根「樹」的輸出:

output_of_tree

這裏是文件(減去在html的有點樣板)

page_a.html :

<head> 
    <link rel="stylesheet" href="styles.css"> 
    <!-- <link rel="stylesheet" href="static/styles.css"> --> 
</head> 
<body> 
    <h1>page_a</h1> 
    <img src="an_image.png"> 
    <!-- <img src="static/an_image.png"> --> 
    <a href="{{ url_for('page_b') }}">to page b</a> 
</body> 

page_b.html:

<head> 
    <link rel="stylesheet" href="styles.css"> 
    <!-- <link rel="stylesheet" href="../../static/styles.css"> --> 
</head> 
<body> 
    <h1>page_b</h1> 
    <img src="../../static/an_image.png"> 
    <!-- <img src="../../static/an_image.png"> --> 
    <a href="{{ url_for('page_a') }}">to page a</a> 
</body> 

INIT的.py:

from flask import Flask 
app = Flask('my_pages') 
import my_pages.views 

runserver.py:

from my_pages import app 
app.run(host='0.0.0.0', port=5000, debug=True) 

views.py:

from my_pages import app 
from flask import render_template 

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

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

styles.css的:

body { 
    background-color: green; 
} 

此版本確實工作時,在page_a.html和page_b.html中,我使用註釋行(而不是上面的行)。

這裏的runserver.py的輸出,當我訪問page_a.html:

"GET /page_a HTTP/1.1" 200 - 
"GET /styles.css HTTP/1.1" 404 - 
"GET /an_image.png HTTP/1.1" 404 - 

和page_b.html。

"GET /pages/page_b/ HTTP/1.1" 200 - 
"GET /pages/page_b/styles.css HTTP/1.1" 404 - 

(最後顯示 'an_image.png' 從我的 '風格' 目錄)

我的問題:我在想什麼?這個設置可以在沒有重大重構的情況下工作嗎?

我當然不想硬編碼每個靜態文件的完整路徑。另外,在實際應用中,這些URL運行深度較深 - 例如,,

http://localhost:5000/book/<id_1>/chapter/<id_2>/page 

非常感謝任何人可能會回覆!

回答

2

您沒有告訴Flask文件在您的靜態文件夾中。最簡單的方法是使用url_for

<link rel="stylesheet" href="{{ url_for('static', filename='styles.css') }}"> 
+0

它的工作原理!非常感謝你的迴應,以及你爲什麼*它能夠工作的清晰,簡潔和可理解的解釋! – jazcap53

1

您可以使用url_for來提供靜態文件。一個例子可以發現here。 PS:除非你製作的東西真的很大,否則使用'/static/file.css'服務應該可以。在生產環境中,最好讓Apache或nginx提供靜態文件。