[英]Static files in a Bottle application cannot be found (404)
我已經審查了所有與此相關的問題,審查了瓶子指南,審查了Google小組的瓶子討論,以及AFAIK,我所做的一切正確。 但是,無論如何,我無法正確加載CSS文件。 我在靜態文件上得到404,找不到http://localhost:8888/todo/static/style.css
,根據下面的目錄結構,情況並非如此。 我正在使用Bottle的版本0.11(不穩定); 有什么我想念的東西嗎?或者這是Bottle中的錯誤?
我的目錄結構:
todo/
todo.py
static/
style.css
我的todo.py:
import sqlite3
from bottle import Bottle, route, run, debug, template, request, validate, static_file, error, SimpleTemplate
# only needed when you run Bottle on mod_wsgi
from bottle import default_app
app = Bottle()
default_app.push(app)
appPath = '/Applications/MAMP/htdocs/todo/'
@app.route('/todo')
def todo_list():
conn = sqlite3.connect(appPath + 'todo.db')
c = conn.cursor()
c.execute("SELECT id, task FROM todo WHERE status LIKE '1';")
result = c.fetchall()
c.close()
output = template(appPath + 'make_table', rows=result, get_url=app.get_url)
return output
@route('/static/:filename#.*#', name='css')
def server_static(filename):
return static_file(filename, root='./static')
我的html:
%#template to generate a HTML table from a list of tuples (or list of lists, or tuple of tuples or ...)
<head>
<link href="{{ get_url('css', filename='style.css') }}" type="text/css" rel="stylesheet" />
</head>
<p>The open items are as follows:</p>
<table border="1">
%for row in rows:
<tr style="margin:15px;">
%i = 0
%for col in row:
%if i == 0:
<td>{{col}}</td>
%else:
<td>{{col}}</td>
%end
%i = i + 1
%end
<td><a href="/todo/edit/{{row[0]}}">Edit</a></td>
</tr>
%end
</table>
我不太了解您的部署。 /Applications/MAMP/htdocs/
路徑,以及代碼中缺少app.run
,建議您在Apache下運行它。 它是生產部署嗎? 您知道,對於開發任務,您應該使用Bottle的內置開發服務器。 添加一個app.run()
對你的最終todo.py
,就大功告成了。
現在,如果您使用的是Apache,最可能的根本原因是以下這一行: static_file(filename, root='./static')
。 使用mod_wsgi,不能保證工作目錄等於您的todo.py
所在的目錄。 實際上,它幾乎永遠不會。
您正在使用數據庫和模板的絕對路徑,對靜態文件使用路徑:
@route('/static/:filename#.*#', name='css')
def server_static(filename):
return static_file(filename, root=os.path.join(appPath, 'static'))
接下來,我不知道您的應用程序的安裝位置。 URL http://localhost:8888/todo/static/style.css
建議掛載點為/todo
,但todo_list
處理程序的路由還是/todo
。 完整路徑應該是http://localhost/todo/todo
嗎? 您的應用程序有/
處理程序嗎?
我還建議避免硬編碼路徑,並將路徑片段合並在一起。 這樣會更干凈:
from os.path import join, dirname
...
appPath = dirname(__file__)
@app.route('/todo')
def todo_list():
conn = sqlite3.connect(join(appPath, 'todo.db'))
...
事實證明,它與Bottle無關,而與加載應用程序的wsgi文件無關。 我沒有將os.path更改為正確的路徑; 它指向wsgi腳本所在的文件夾。 顯然,那里沒有css文件。 在sgi腳本中更正目錄后,一切正常。 換一種說法:
os.chdir(os.path.dirname(__file__))
需要成為
os.chdir('Applications/MAMP/htdocs/todo')
因為我的wsgi腳本位於與應用程序本身不同的目錄中(mod_wsgi建議采用這種方法)。 謝謝各位的幫助!
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.