繁体   English   中英

在Bottle应用程序中找不到静态文件(404)

[英]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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM