我最近从Flask切换到Bottle,我遇到了一些问题。
@error
无法正常工作的错误页面我的文件树看起来像:
dev
|
|_db
| |_dev.db
|
static
|
|_styles
|
|_js
| |_script.js
|
|
views
|
|_index.tpl
|
|
|_about.tbl
|
|
|_404.tbl
|
application.py
这是我的application.py
:
# Main application file
# Created by James Parsons 2/23/15
from bottle import error
from bottle import *
from bottle.ext import sqlite
app = Bottle()
db_plugin = sqlite.Plugin(dbfile="./dev/db/dev.db")
app.install(db_plugin)
@route("/static/<filepath:path>")
def server_static(filepath):
# FIXME Bottle is not routing statics correctly
return static_file(filepath, root="/static/")
@error(404)
def error_404():
# FIXME Bottle is not displaying errors correctly
return template("404")
@app.route("/")
def index():
return template("index")
# TODO Work on index page
@app.route("/about")
def about():
return template("about")
# TODO Work on about page
# FUTURE Run on CGI server
run(app, host="localhost", port="80")
script.js
无法从/static/js/script.js
获取,当我转到不存在的路线时,我没有收到自定义错误页面,但默认404错误。我究竟做错了什么?我该如何解决?
答案 0 :(得分:3)
在您的代码中,您没有对静态文件中的app
对象和404错误路由使用装饰器方法。所以
@route
应该是
@app.route
和error
相同。
您也可能打算从相对路径
中获取静态文件e.g。
return static_file(filename, root='./static/')
或
return static_file(filename, root='static/')
你告诉瓶子要查看顶级目录/static/
以下是适合我的完整代码
# Main application file
from bottle import error
from bottle import *
from bottle.ext import sqlite
app = Bottle()
#db_plugin = sqlite.Plugin(dbfile="./dev/db/dev.db")
#app.install(db_plugin)
@app.route('/static/<filename:path>')
def send_static(filename):
return static_file(filename, root='./static/')
@app.error(404)
def error_404(error):
return template("404")
@app.route("/")
def index():
return template("index")
@app.route("/about")
def about():
return template("about")
# FUTURE Run on CGI server
run(app, host="localhost", port="8080")
注意:我禁用了sqlite的东西,因为它不适用于这个问题,我使用端口值8080来避免需要超级用户权限来访问端口。你应该准备好后再改回来。
在index.tpl
文件中,我引用了js脚本,如
<script src="static/js/script.js" ></script>
希望这足以解决您的问题。