【发布时间】:2014-02-25 15:56:22
【问题描述】:
我正在尝试使用 Bottle/MongoDB 从 MongoDB 大学课程之一扩展博客引擎。
我添加了页眉和页脚模板,并添加了一些简单的 JS、CSS 和图像。这些在除 show_post 视图之外的所有模板上都可以正常工作。它的设置方式似乎是传递给函数的值包括静态文件(css、js 和 png)以及博客文章本身的 URL 变量。
python 控制台的值是:
- 即将查询永久链接 = TLxrBfyxTZjqOKqxgnUP
- 1.0.0.127.in-addr.arpa - - [25/Feb/2014 15:08:09] "GET /post/TLxrBfyxTZjqOKqxgnUP HTTP/1.1" 200 37682
- 即将查询 permalink = style.css
- 1.0.0.127.in-addr.arpa - - [25/Feb/2014 15:08:09] "GET /post/style.css HTTP/1.1" 303 0
- 即将查询 permalink = blog.js
- 1.0.0.127.in-addr.arpa - - [25/Feb/2014 15:08:09] "GET /post/blog.js HTTP/1.1" 303 0
- 即将查询 permalink = BL_logo.png
- 1.0.0.127.in-addr.arpa - - [25/Feb/2014 15:08:09] "GET /post/BL_logo.png HTTP/1.1" 303 0
- 1.0.0.127.in-addr.arpa - - [25/Feb/2014 15:08:09] "GET /post_not_found HTTP/1.1" 200 21
- 1.0.0.127.in-addr.arpa - - [25/Feb/2014 15:08:09] "GET /post_not_found HTTP/1.1" 200 21
- 1.0.0.127.in-addr.arpa - - [25/Feb/2014 15:08:09] "GET /post_not_found HTTP/1.1" 200 21
有问题的代码是:
# Displays a particular blog post
@bottle.get("/post/<permalink>")
def show_post(permalink="notfound"):
cookie = bottle.request.get_cookie("session")
username = sessions.get_username(cookie)
permalink = cgi.escape(permalink)
print "about to query on permalink = ", permalink
post = posts.get_post_by_permalink(permalink)
if post is None:
bottle.redirect("/post_not_found")
# init comment form fields for additional comment
comment = {'name': "", 'body': "", 'email': ""}
return bottle.template("entry_template", dict(post=post, username=username, errors="", comment=comment))
如果“永久链接”是文件而不是查询字符串中的值,我该如何防止函数被调用?
谢谢, 标记
回答
非常感谢 Ron 在下面的回答为我指明了正确的方向。
我的错误归结为静态文件的路径不正确。我通过导入 os 使路径动态化,然后将根值更改为 os.path.join(os.getcwd(), 'static/js') 并将我的 header.tpl 中的文件路径设为绝对,例如“/style.css”。
@bottle.get('/<filename:re:.*\.css>')
def stylesheets(filename):
rootPath=os.path.join(os.getcwd(), 'static/css')
return bottle.static_file(filename, root=rootPath)
【问题讨论】: