个CherryPy应用程序中将REST调度程序与默认调度程序结合

个CherryPy应用程序中将REST调度程序与默认调度程序结合

本文介绍了在单个CherryPy应用程序中将REST调度程序与默认调度程序结合的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试让CherryPy通过 cherrypy.dispatch.MethodDispatcher()和所有其他请求(例如/)到一些默认的调度程序.

I'm trying to make CherryPy to handle request to /api via cherrypy.dispatch.MethodDispatcher() and all other request (like /) to some default dispatcher.

阅读CherryPy的文档后,我不知道如何执行此操作.他们仅分别使用两种路由方法,但这是一件非常基本的事情,我认为它必须协同工作.

After reading CherryPy's doc I have no idea how to do this. They use both routing methods only separately but this is such a basic thing that I believe it has to work together.

#!/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.

By calling curl 'http://localhost:8080/' it gives me Hello world which is correct.
But calling curl -X POST 'http://localhost:8080/api' returns just 404.

顺便说一句,这个问题完全相同,没有任何答案 CherryPy MethodDispatcher与多个网址路径.

By the way, the're eaxctly the same question without any answer CherryPy MethodDispatcher with multiple url paths.

推荐答案

最后,我解决了它.奇怪的是,我不得不使用注释 @ cherrypy.expose 公开 index 方法(以及 Root 类中的所有其他方法),而不仅仅是通过像 RestAPI 类中那样设置 exposed = True .我不知道为什么.

Finally I solved it. The weird thing was that I had to expose index method (and all other methods in Root class) using annotation @cherrypy.expose and not just by setting exposed = True like in RestAPI class. I don't know why.

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

To properly test POST handler I didn't have to pass any variables but still I had to set Content-length: 0 header.

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的正确方法:

Proper way to test POST using cURL:

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

这篇关于在单个CherryPy应用程序中将REST调度程序与默认调度程序结合的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-14 02:59