使用WSGI的Cherrypy路由

2024-06-17 12:33:41 发布

您现在位置:Python中文网/ 问答频道 /正文

我尝试将某些url路由到一个嫁接的WSGI应用程序,并将子url路由到一个普通的cherrypy页面处理程序。在

我需要以下路线上班。所有其他路由都应该返回404。在

  • /api->WSGI
  • /api?wsdl>;WSGI
  • /api/goodurl->页面处理程序
  • /api/badurl->404错误

安装在/api上的WSGI应用程序是一个基于SOAP的遗留应用程序。它需要接受吗?wsdl参数,但仅此而已。在

我正在/api/some\u resource上编写一个新的restfulapi。在

我遇到的问题是,如果资源不存在,它最终会将错误的请求发送到遗留的soap应用程序。最后一个示例“/api/badurl”最终将转到WSGI应用程序。在

有没有办法告诉cherrypy只将前两条路由发送到WSGI应用程序?

我为我的问题写了一个简单的例子:

import cherrypy

globalConf = {
    'server.socket_host': '0.0.0.0',
    'server.socket_port': 8080,
}
cherrypy.config.update(globalConf)

class HelloApiWsgi(object):
    def __call__(self, environ, start_response):
        start_response('200 OK', [('Content-Type', 'text/html')])
        return ['Hello World from WSGI']

class HelloApi(object):
    @cherrypy.expose
    def index(self):
        return "Hello from api"

cherrypy.tree.graft(HelloApiWsgi(), '/api')
cherrypy.tree.mount(HelloApi(), '/api/hello')

cherrypy.engine.start()
cherrypy.engine.block()

下面是一些单元测试:

^{pr2}$

输出:

nosetests test_rest_api.py
F..
======================================================================
FAIL: testBadUrl (webserver.test_rest_api.TestRestApi)
----------------------------------------------------------------------
Traceback (most recent call last):
  File line 25, in testBadUrl
    self.assertEqual(r.status_code, 404)
AssertionError: 200 != 404
-------------------- >> begin captured stdout << ---------------------
Hello World from WSGI

Tags: fromselfapi应用程序url处理程序wsgi路由
1条回答
网友
1楼 · 发布于 2024-06-17 12:33:41

前言:我不得不提到,我希望每个人都能以这样一种完整的形式提出问题,以验证答案:-)

超出CherryPy范围的解决方案:

  • 在前端服务器进行URL预处理,如nginx
  • 创建自己的WSGI middleware,即将旧的WSGI应用包装到另一个将过滤url的应用程序中

后者可能是首选的方法,但这是CherryPy的方法。文档部分host a foreign WSGI application in CherryPy说:

You cannot use tools with a foreign WSGI application.

也不能设置自定义调度程序。但您可以将应用程序树的子类化。在

#!/usr/bin/env python


import cherrypy


class Tree(cherrypy._cptree.Tree):

  def __call__(self, environ, start_response):
    # do more complex check likewise
    if environ['PATH_INFO'].startswith('/api/badurl'):
      start_response('404 Not Found', [])
      return []

    return super(Tree, self).__call__(environ, start_response)

cherrypy.tree = Tree()


globalConf = {
  'server.socket_host': '0.0.0.0',
  'server.socket_port': 8080,
}
cherrypy.config.update(globalConf)


class HelloApiWsgi:

  def __call__(self, environ, start_response):
    start_response('200 OK', [('Content-Type', 'text/html')])
    return ['Hello World from WSGI']

class HelloApi:

  @cherrypy.expose
  def index(self):
    return "Hello from api"


cherrypy.tree.graft(HelloApiWsgi(), '/api')
cherrypy.tree.mount(HelloApi(), '/api/hello')


if __name__ == '__main__':
  cherrypy.engine.signals.subscribe()
  cherrypy.engine.start()
  cherrypy.engine.block()

相关问题 更多 >