我正在试验Bottle / MongoDB,从一个MongoDB大学课程中扩展Blog Engine。
我添加了一个标题&页脚模板并添加了一些简单的JS,CSS和图像。这些在show_post视图以外的所有模板上都可以正常工作。它似乎设置的方式是传递给函数的值包括静态文件(css,js& png)以及博客帖子本身的URL变量。
python控制台的值是:
有问题的代码是:
# 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))
如果'permalink'是文件而不是查询字符串中的值,我怎么能阻止调用该函数呢?
谢谢, 标记
ANSWER
非常感谢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)
答案 0 :(得分:0)
由于您已将资产置于/post
之下,因此它们与您的/post/<permalink>
路线相冲突。
通常,您将从自己的目录中提供资产(css,js,png);像/static/css/foo.css
这样的东西。这就是我在这里推荐的。
有些事情如下:
@bottle.get("/post/<permalink>")
def show_post(permalink="notfound"):
# code to generate a post page goes here
@bottle.get("/static/<file_name:path>"):
def static_file(file_name):
return bottle.static_file(file_name, "/full/path/to/your/static/file/root/")
相关的Bottle文档为here;或者查看许多posts describing how中的一个来提供来自Bottle的静态文件。