python - 在 Cherrypy 中运行多个类

标签 python cherrypy

我正在尝试构建一个带有索引等的小型站点以及我想要的/api 中的 api。

例如:

class Site(object):
    @cherrypy.expose
    def index(self):
        return "Hello, World!"
    @cherrypy.expose
    def contact(self):
        return "Email us at..."
    @cherrypy.expose
    def about(self):
        return "We are..."

class Api(object):
    @cherrypy.expose
    def getSomething(self, something):
        db.get(something)
    @cherrypy.expose
    def putSomething(self, something)

所以,我希望能够访问 mysite.com/contact 和 mysite.com/Api/putSomething

如果我使用 cherrypy.quickstart(Site()),我只会获取 Site 下的页面。

我认为有一种方法可以将 Api 类映射到/Api 下,但我找不到它。

最佳答案

更新(2017 年 3 月 13 日):下面的原始答案已经过时,但我保留原样以反射(reflect)提出的原始问题。

The official documentation now has a proper guide on how to achieve it.


原答案:

查看默认调度程序。 The entire documentation for Dispatching.

引用自文档:

root = HelloWorld()
root.onepage = OnePage()
root.otherpage = OtherPage()

In the example above, the URL http://localhost/onepage will point at the first object and the URL http://localhost/otherpage will point at the second one. As usual, this search is done automatically.

This link gives even more detail on it with a complete example shown below.

import cherrypy

class Root:
    def index(self):
        return "Hello, world!"
    index.exposed = True

class Admin:
    def user(self, name=""):
        return "You asked for user '%s'" % name
    user.exposed = True

class Search:
    def index(self):
        return search_page()
    index.exposed = True

cherrypy.root = Root()
cherrypy.root.admin = Admin()
cherrypy.root.admin.search = Search()

关于python - 在 Cherrypy 中运行多个类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14661217/

相关文章:

python - 在 scipy/numpy 中求解具有已知 y 的多项式的 x 值

python - 如何将独立的 Python 脚本集成到 Rails 应用程序中?

python - pylibmc : 'Assertion "ptr->query_id == query_id + 1"failed for function "memcached_get_by_key"'

python - 如何在 Python 3 中对 CherryPy webapp 进行单元测试?

python - 如何使用将服务器链接到在暴露的本地主机上运行的 flask 应用程序

python - 按模式读取文件

python - PANDAS 网页抓取多个页面

Python Cherrypy 访问日志轮换

Pythoncherpy,解析query_string

python-3.x - CherryPy上传文件