路由Cherrypy Web应用程序(未通过道路资源)

时间:2014-04-14 23:39:59

标签: python url routes cherrypy dispatcher

我花了4天多的时间试图弄清楚这一点,但是我的每一次尝试都失败了,所以我认为我可以真正使用你的一些帮助。

在下面的代码中,Storm是一个具有函数submit_data()的应用程序,它根据在实例化时传递的pagename参数和从xmlhttp GET传递的idx参数从数据库中获取数据请求Javascript。

基本上我想要一个带有Root类的索引页面,以及从XML文件中读取一堆具有不同Storm参数的类似pagename页面。

我正在使用RoutesDispatcher,因为我也使用XML文件参数化页面名称(地址)。

当我使用/storm作为地址时,它甚至无法工作,因为名称冲突,所以我将地址设置为/st/

现在它显示标题,但根本找不到submit_data函数。 Chrome控制台会引发以下错误。

Failed to load resource: the server responded with a status of 404 (Not Found) http://localhost:8080/st/submit_data?idx=0
Failed to load resource: the server responded with a status of 404 (Not Found) http://localhost:8080/st/submit_data?idx=2
Failed to load resource: the server responded with a status of 404 (Not Found) http://localhost:8080/st/submit_data?idx=1

我如何构建这个,以便当我在浏览器中键入localhost:8080 / st时,html / javascript模板storm.html会查找submit_data函数并调用它并将其显示在网页上?在我开始路由之前,它完全正常。

class Storm(object):
    pagename = ""
    def __init__(self, pagename):
        self.pagename = pagename

    @cherrypy.expose
    @cherrypy.tools.mako(filename="storm.html", directories=MEDIA_DIR)
    def index(self, name=None):
        return {'size': len(params["dashboards"][self.pagename])}

    @cherrypy.expose 
    def submit_data(self, idx):
        idx = int(idx)
        chart = params["dashboards"][self.pagename][idx]
        # Sample page that displays the number of records in "table" 
        # Open a cursor, using the DB connection for the current thread 
        c = cherrypy.thread_data.dbdict[chart["dbname"]].cursor() 
        print 'query being executed......'
        c.execute(chart["command"])
        print 'query being fetched......'
        res = c.fetchall()
        c.close()

        # construct a JSON object from query result
        jsres = []
        jsres.append(chart["selected"])
                       .
                       .
                       .

        return json.dumps(jsres)

class Root(object):
    #storm = Storm("first")
    @cherrypy.expose
    @cherrypy.tools.mako(filename="index.html", directories=MEDIA_DIR)
    def index(self, name=None):
        return {}

config = {'/media':
                {'tools.staticdir.on': True,
                 'tools.staticdir.dir': MEDIA_DIR,
                }
        }

root = Root()
storm = Storm("first") 
mapper = cherrypy.dispatch.RoutesDispatcher()
mapper.connect('home','/',controller=root, action='index')
mapper.connect('st','/st/',controller=storm, action='index')
conf = {'/': {'request.dispatch': mapper}}
app=cherrypy.tree.mount(root=None,config=conf)
cherrypy.quickstart(app)

1 个答案:

答案 0 :(得分:1)

mapper.connect('st','/st/submit_data',controller=storm, action='submit_data')

Routes明确列出了所有处理程序,因此也不需要公开。基于此示例,您可能不需要路由调度程序。安装了多个根的默认调度程序可以正常工作。