在cherrypy中的静态文件

时间:2015-01-22 10:32:58

标签: python cherrypy static-content

我正在使用Cherrypy 3.2.3,Python 2.7.3。 代码:

from jinja2 import Environment, FileSystemLoader
import cherrypy
import os

folder=os.path.abspath(os.curdir)

class Root(object):
    @cherrypy.expose
    def index(self):
        j2_env = Environment(loader=FileSystemLoader(folder), trim_blocks=True) 
        return j2_env.get_template('index.html').render()



cherrypy.config.update({
    'environment': 'production',
    'log.screen': True,
    'server.socket_host': '127.0.0.1',
    'server.socket_port': 28807,
})

conf = {'static': {'tools.staticdir.on': True,
                   'tools.staticdir.dir' : os.path.join(folder, 'static'),
               'tools.staticdir.content_types' : {'html': 'application/octet-stream'}}}

cherrypy.config.update(conf)

print cherrypy.config
print os.path.join(folder, 'static')
cherrypy.quickstart(Root(), '/', config = conf)

输出:

  

{'environment':'production','tools.trailing_slash.on':是的,'request.show_tracebacks':错误,'log.screen':是的,'tools.encode.on':是的,'工具' .log_tracebacks.on':是的,'server.socket_port':28807,'checker.on':错误,'静态':{'tools.staticdir.dir':'/ home / ivan / cherypy / cherryblocks / static', 'tools.staticdir.content_types':{'html':'application / octet-stream'},'tools.staticdir.on':True},'server.socket_host':'127.0.0.1','request.show_mismatched_pa​​rams' :False,'tools.log_headers.on':错误,'engine.autoreload_on':False}

     

/家庭/伊万/ cherypy / cherryblocks /静态

我试着获得http://127.0.0.1:28807/static/style.css

  

127.0.0.1 - - [22 / Jan / 2015:13:24:38]“GET /static/style.css HTTP / 1.1”404 730“”“Mozilla / 5.0(X11; Linux x86_64; rv:24.0) )Gecko / 20100101 Firefox / 24.0“

错误404。

但我可以打开/home/ivan/cherypy/cherryblocks/static/style.css:

stat /home/ivan/cherypy/cherryblocks/static/style.css

  

文件:«/home/ivan/cherypy/cherryblocks/static/style.css»     大小:2556

cherrypy如何提供静态文件?

1 个答案:

答案 0 :(得分:0)

应用级配置字典的密钥应该是服务器相对路径,例如/static

conf = {
  '/static' : {
    'tools.staticdir.on' : True,
    'tools.staticdir.dir' : os.path.join(folder, 'static'),
    'tools.staticdir.content_types' : {'html': 'application/octet-stream'}
  }
}

另外,我建议您在提出问题之前首先搜索StackOverflow,因为它有quite some CherryPy static content serving questions