Cherrypy映射URL功能

时间:2012-03-02 01:39:59

标签: python http-status-code-404 cherrypy

我想在网站上使用Cherrypy,但是我在使用python代码中的函数映射我要显示的页面的url时遇到了一些问题。

现在我有了这段代码

#!/usr/bin/env python

import os
localDir = os.path.dirname(__file__)
absDir = os.path.join(os.getcwd(), localDir)


import cherrypy
from genshi.template import TemplateLoader
loader = TemplateLoader('../html', auto_reload=True)

class Root(object):

    @cherrypy.expose
    def index(self):
        tmpl = loader.load('index.html')
        return tmpl.generate().render('html', doctype='html')

    @cherrypy.expose
    def upload(self, datafile):
        #do something
        ...
        return out % (size, datafile.filename, datafile.content_type)

    cherrypy.root.index = index
    cherrypy.root.upload = upload


conf = os.path.join(os.path.dirname(__file__), 'server.config')

cherrypy.quickstart(Root(), '/', config=conf)

配置文件是这样的:

[/index.html]
tools.staticfile.on = True
tools.staticfile.filename = "/path-to-file/html/index.html"

[/impemails.html]
tools.staticfile.on = True
tools.staticfile.filename = "/path-to-file/html/impemails.html"

[/css/style.css]
tools.staticfile.on = True
tools.staticfile.filename = "/path-to-file/css/style.css"

[/css/index.css]
tools.staticfile.on = True
tools.staticfile.filename = "/path-to-file/css/index.css"

[/css/imp.css]
tools.staticfile.on = True
tools.staticfile.filename = "/path-to-file/css/imp.css"

对于配置文件中指定的所有文件没有问题,但当我尝试使用链接http://localhost:8080/upload访问上传时,我收到“404 Not found Message”

Traceback (most recent call last):
  File "/usr/local/lib/python2.7/dist-packages/cherrypy/_cprequest.py", line 656, in respond
    response.body = self.handler()
  File "/usr/local/lib/python2.7/dist-packages/cherrypy/lib/encoding.py", line 188, in __call__
    self.body = self.oldhandler(*args, **kwargs)
  File "/usr/local/lib/python2.7/dist-packages/cherrypy/_cperror.py", line 386, in __call__
    raise self
NotFound: (404, "The path '/upload' was not found.")

我尝试了许多不同的方法来解决这个问题,如教程http://docs.cherrypy.org/dev/concepts/dispatching.html所示,但我失败了。 我想我缺少一些未在教程中报告的配置。

有人提出一些想法吗? 提前谢谢

1 个答案:

答案 0 :(得分:3)

我的不好,我误解了一些配置。 我已经解决了这个问题:

class Root(object):

    @cherrypy.expose
    def index(self):
        tmpl = loader.load('index.html')
        return tmpl.generate().render('html', doctype='html')


@cherrypy.expose
def upload(couchdb, maillist, datafile):
    return "upload file"

conf = os.path.join(os.path.dirname(__file__), 'server.config')

root = Root()
root.upload = upload

cherrypy.tree.mount(root, '/', config=conf)
cherrypy.engine.start()
cherrypy.engine.block()

基本上我刚把这个函数移到了Root类之外,并添加了root.upload = upload的路径

现在可行。