使用WSGI进行Cherrypy路由

时间:2015-06-30 17:13:32

标签: python cherrypy python-routes

我正在尝试将某些URL路由到移植的WSGI应用程序,并将子URL路由到普通的cherrypy页面处理程序。

我需要以下路线才能工作。所有其他路线应返回404.

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

在/ api上安装的WSGI应用程序是一个基于SOAP的传统应用程序。它需要接受?wsdl参数,但这就是全部。

我正在/ api / some_resource写一个新的RESTful api。

我遇到的问题是,如果资源不存在,它最终会将错误请求发送到传统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()

以下是一些单元测试:

import unittest
import requests

server = 'localhost:8080'

class TestRestApi(unittest.TestCase):

    def testWsgi(self):
        r = requests.get('http://%s/api?wsdl'%(server))
        self.assertEqual(r.status_code, 200)
        self.assertEqual(r.text, 'Hello World from WSGI')

        r = requests.get('http://%s/api'%(server))
        self.assertEqual(r.status_code, 200)
        self.assertEqual(r.text, 'Hello World from WSGI')

    def testGoodUrl(self):
        r = requests.get('http://%s/api/hello'%(server))
        self.assertEqual(r.status_code, 200)
        self.assertEqual(r.text, 'Hello from api')

    def testBadUrl(self):
        r = requests.get('http://%s/api/badurl'%(server))
        self.assertEqual(r.status_code, 404)

输出:

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

1 个答案:

答案 0 :(得分:3)

前言:我不能不提及我希望每个人都能以完整的形式提出问题,并提供验证答案的方法: - )

CherryPy范围内的解决方案:

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

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

  

您不能将工具与外部WSGI应用程序一起使用。

此外,您无法设置自定义调度程序。但是你可以子类化应用程序树。

#!/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()