【问题标题】:cherrypy, serve css file, wrong pathcherrypy,提供 css 文件,路径错误
【发布时间】:2014-11-01 10:22:44
【问题描述】:

在使用 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"}
})

当我启动我的脚本时,有 wrtten:

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'

但 root + dir 是正确的路径 (Users/mypc/Desktop/data/css) 我错在哪里以及为什么我无法通过浏览器打开我的 CSS?

提前致谢

【问题讨论】:

    标签: python path cherrypy static-content


    【解决方案1】:

    这里是the relevant documentation section。它说:

    CherryPy 总是需要它所服务的文件或目录的绝对路径。 如果您要配置多个静态部分但位于同一根目录中 目录,您可以使用以下快捷方式...tools.staticdir.root

    在其他作品中,当您提供 tools.staticdir.root 时,所有底层 tools.staticdir.dir 条目不得是绝对的,即以斜线开头,这是 CherryPy Checker 警告您的内容。

    以下内容就足够了。只需将 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)
    

    【讨论】:

    • 完美!谢谢!我只需要将根部分添加到配置中!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-02-02
    • 2010-12-30
    • 2021-03-22
    • 2012-03-23
    • 1970-01-01
    相关资源
    最近更新 更多