向运行中的gevent pywsgi.WSGIServer添加更多应用

0 投票
1 回答
727 浏览
提问于 2025-04-18 12:57

我有一个应用程序,结构大概是这样的:

application = DirectoryApp(
                           'app/static',
                           index_page='index.html',
                           hide_index_with_redirect=True)

if __name__ == '__main__':
    config = get_config()

    from gevent import pywsgi
    server = pywsgi.WSGIServer((config['host'], config['port']), application)
    server.serve_forever()

我想知道,服务器启动后,是否可以通过代码再添加一个应用程序到这个堆栈里?我想做的事情大概是这样的:

# Create new application class
class AnotherController((object):
    def __init__(self, app):
        self.app = app

    def __call__(self, environ, start_response):
        from webob import Request, Response
        req = Request(environ)

        if req.method == 'GET' and req.path_info.startswith('/anothercontroller'):
            res = Response(
                body='Hello World, Another Controller!',
                status=200,
                content_type='text/plain'
            )

            return res(environ, start_response)

        return self.app(environ, start_response)

def add_application():
    global application
    application = AnotherController(application)

# Add the application to the stack after the fact it is already running
add_application()

问题是,这样做之后,新加的应用程序类的 __call__ 方法似乎根本没有被调用。

我感觉我并没有真正影响到服务器正在使用的那个堆栈……

1 个回答

-1

你可以使用paste的级联功能来加载多个wsgi应用程序:http://pythonpaste.org/modules/cascade.html

下面是一个使用gevent.pywsgi的代码示例:

def http_server():
    static_app = paste.urlparser.StaticURLParser(
        os.path.join(twit.__path__[0], "static"))
    apps = paste.cascade.Cascade([static_app, search.app])
    http_server = gevent.pywsgi.WSGIServer(
        ('', 8000), apps)
    http_server.start()

撰写回答