【问题标题】:bottle - static files causing 303 errors瓶子 - 导致 303 错误的静态文件
【发布时间】: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)

【问题讨论】:

    标签: python bottle


    【解决方案1】:

    因为您已将资产置于 /post 下,它们与您的 /post/&lt;permalink&gt; 路由冲突。

    通常,您会从它们自己的目录中提供资源(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 的静态文件。

    【讨论】:

    • 您好罗恩,感谢您的回答。这就是我提供资产的方式 - @bottle.get('/') def javascripts(filename): return bottle.static_file(filename, root='static/js')
    猜你喜欢
    • 2018-12-09
    • 1970-01-01
    • 2012-05-16
    • 2015-11-18
    • 1970-01-01
    • 2014-09-28
    • 1970-01-01
    • 1970-01-01
    • 2017-05-06
    相关资源
    最近更新 更多