Skip to main content
 首页 » 编程设计

python之使用 WSGI 在 Python 中反向代理

2025年05月04日11Leo_wl

应用程序,使用 Flask 构建。 我想要以下路由:

"/"     -> my Flask app 
"/foo/" -> Reverse proxy toward http://bar/ 

到目前为止,我没有任何反向代理,所以我的应用程序看起来像:

import app 
[...] 
if __name__ == '__main__': 
    app.app.secret_key = 'XXX' 
    app.app.run(debug=True, use_reloader=False) 

我希望整个项目只在 python 中。我不想要任何 Apache 或 nginx 堆栈(该项目不应该在公共(public)网络上)。我看到我可以使用 Python WSGI 服务器,例如 cherrypy 中的“wsgiserver”,所以我的应用程序将是:

from cherrypy import wsgiserver 
import app 
 
d = wsgiserver.WSGIPathInfoDispatcher({ 
    '/': app.app.wsgi_app 
}) 
server = wsgiserver.CherryPyWSGIServer(('0.0.0.0', 8080), d) 
 
if __name__ == '__main__': 
      server.start() 

如果我想在“/foo”中添加反向代理,我想我只需要:

from cherrypy import wsgiserver 
import app 
 
d = wsgiserver.WSGIPathInfoDispatcher({ 
    '/': app.app.wsgi_app, 
    '/foo/': SOME_WSGI_REVERSE_PROXY 
}) 
server = wsgiserver.CherryPyWSGIServer(('0.0.0.0', 8080), d) 
 
if __name__ == '__main__': 
      server.start() 

所以我的问题是:

  • 是否有任何用 python 编写的符合 WSGI 标准的反向代理? (我不知道是否存在 SOME_WSGI_REVERSE_PROXY)
  • 这种实现方式是否可行?

回答:

正如accepted anwser所提到的,这里是最终代码:

from cherrypy import wsgiserver 
import wsgiproxy.app 
import app 
app = app.app.wsgi_app 
proxy = wsgiproxy.app.WSGIProxyApp("http://bar/") 
d = wsgiserver.WSGIPathInfoDispatcher({ 
    '/': app, 
    '/foo/':proxy 
}) 
server = wsgiserver.CherryPyWSGIServer(('0.0.0.0', 8080), d) 
 
if __name__ == '__main__': 
   try: 
      server.start() 
   except KeyboardInterrupt: 
      server.stop() 

请您参考如下方法:

请参阅粘贴代理中间件。