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

编程入门 行业动态 更新时间:2024-10-27 18:24:37
本文介绍了在单个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'localhost:8080/',它为我提供了 Hello world ,这是正确的.但是调用 curl -X POST'localhost:8080/api'只会返回404.

By calling curl 'localhost:8080/' it gives me Hello world which is correct. But calling curl -X POST '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" localhost:8080/api

更多推荐

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

本文发布于:2023-11-25 08:05:08,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1628969.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:程序   中将   应用程序   CherryPy   REST

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!