cherrypy,服务css文件,路径错误

0 投票
1 回答
1531 浏览
提问于 2025-05-01 00:16

我在用CherryPy管理的HTML页面上加载CSS时遇到了问题。

这是我的情况:

class HelloWorld(object):
   @cherrypy.expose
   def index(self):
     return "Hello world!"


   @cherrypy.expose
   def sc(self):
     Session = sessionmaker()
     session = Session(bind=engine)
   ...
   ...
if __name__ == '__main__':
cherrypy.quickstart(HelloWorld(),config={
'/':
{'tools.staticdir.root': True,
'tools.staticdir.root': "Users/mypc/Desktop/data"},
'/css':
{ 'tools.staticdir.on':True,'tools.staticdir.dir':"/css" }, 
'/style.css':
{ 'tools.staticfile.on':True,
'tools.staticfile.filename':"/style.css"}
})

当我运行我的脚本时,出现了:

CherryPy Checker:
dir is an absolute path, even though a root is provided.
'/css' (root + dir) is not an existing filesystem path.
section: [/css]
root: 'Users/mypc/Desktop/data'
dir: '/css'

但是根目录加上目录是正确的路径(Users/mypc/Desktop/data/css)。我哪里出错了,为什么我在浏览器中无法打开我的CSS呢?

提前谢谢你们!

暂无标签

1 个回答

1

这里有一段相关的文档内容,链接在这里:查看文档。文档里说:

CherryPy总是需要你提供文件或目录的绝对路径。如果你有几个静态文件需要配置,但它们都在同一个根目录下,你可以使用以下快捷方式... tools.staticdir.root

换句话说,当你提供了tools.staticdir.root后,所有的tools.staticdir.dir条目就不能是绝对路径,也就是说不能以斜杠开头,这就是CherryPy检查器给你的警告。

下面的内容就足够了。只需要把你的CSS文件放在这个目录里就行。

#!/usr/bin/env python
# -*- coding: utf-8 -*-


import os

import cherrypy


path   = os.path.abspath(os.path.dirname(__file__))
config = {
  'global' : {
    'server.socket_host' : '127.0.0.1',
    'server.socket_port' : 8080,
    'server.thread_pool' : 8
  },
  '/css' : {
    'tools.staticdir.on'  : True,
    'tools.staticdir.dir' : os.path.join(path, 'css')
  }
}


class App:

  @cherrypy.expose
  def index(self):
    return 'Hello world!'


if __name__ == '__main__':
  cherrypy.quickstart(App(), '/', config)

撰写回答