【问题标题】:Combining REST dispatcher with the default one in a single CherryPy app在单个 CherryPy 应用程序中将 REST 调度程序与默认调度程序相结合
【发布时间】:2014-02-27 10:51:39
【问题描述】:

我正在尝试让 CherryPy 处理通过cherrypy.dispatch.MethodDispatcher()/api 的请求以及对某个默认调度程序的所有其他请求(如/)。

阅读 CherryPy 的文档后,我不知道该怎么做。他们只分别使用这两种路由方法,但这是一个非常基本的东西,我相信它必须一起工作。

#!/usr/local/bin/python2.7
import cherrypy


class Root(object):
    @cherrypy.expose
    def index(self):
        return 'Hello world'

class RestAPI(object):
    @cherrypy.expose
    def POST(self, blah):
        return 'ok'

cherrypy.config.update({
    'global': {
        'environment': 'production',
        'server.socket_host': '127.0.0.1',
        'server.socket_port': 8080,
    }
})


root = Root()
root.api = RestAPI()

conf = {
    '/api': {
        'request.dispatch': cherrypy.dispatch.MethodDispatcher()
    }
}

cherrypy.quickstart(root, '', config=conf)

通过调用curl 'http://localhost:8080/',它给了我Hello world,这是正确的。
但是调用 curl -X POST 'http://localhost:8080/api' 只返回 404。

顺便说一句,这完全是同一个问题,没有任何答案CherryPy MethodDispatcher with multiple url paths

【问题讨论】:

    标签: python cherrypy


    【解决方案1】:

    我来晚了,也许你已经发现了错误。您的班级RestApi 必须公开。该装饰器不适用于MethodDispatcher

    【讨论】:

      【解决方案2】:

      终于解决了。奇怪的是,我必须使用注解 @cherrypy.expose 来公开 index 方法(以及 Root 类中的所有其他方法),而不仅仅是像在 RestAPI 类中那样设置 exposed = True。我不知道为什么。

      为了正确测试 POST 处理程序,我不必传递任何变量,但我仍然必须设置 Content-length: 0 标头。

      class Root(object):
      
          @cherrypy.expose
          def index(self):
              return 'Hello world'
      
      
      class RestAPI(object):
      
          exposed = True
      
          def POST(self):
              return 'post'
      
          def GET(self):
              return 'get'
      
      
      cherrypy.config.update({
          'global': {
              'environment': 'test_suite',
              'server.socket_host': '127.0.0.1',
              'server.socket_port': 8080,
          }
      })
      
      cherrypy.tree.mount(Root())
      
      cherrypy.tree.mount(RestAPI(), '/api',
          {'/':
              {'request.dispatch': cherrypy.dispatch.MethodDispatcher()}
          }
      )
      
      cherrypy.engine.start()
      cherrypy.engine.block()
      

      使用 cURL 测试 POST 的正确方法:

      curl -X POST --header "Content-length: 0" http://localhost:8080/api

      【讨论】:

      • 真正的解决方法是将“request.dispatch”配置移至根配置。您不能在子路径中指定不同的调度程序,因为在调度时仍在收集配置——鸡和蛋。您必须仅在“/”或“全局”处指定调度程序。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2023-03-29
      • 1970-01-01
      • 1970-01-01
      • 2023-04-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多