HTTP代理

许多人喜欢使用独立的python http服务器,并通过nginx、apache等代理该服务器。

一个非常稳定的python服务器是cherrypy。文档的这一部分向您展示了如何将WSGi应用程序与Cherrypy WSGi服务器结合起来,以及如何配置用于代理的Web服务器。

创建一个 .py 服务器

要运行应用程序,需要 start-server.py 启动wsgi服务器的文件。

它看起来像是这样的:

from cherrypy import wsgiserver
from yourapplication import make_app
server = wsgiserver.CherryPyWSGIServer(('localhost', 8080), make_app())
try:
    server.start()
except KeyboardInterrupt:
    server.stop()

如果现在启动服务器将监听的文件 localhost:8080 .请记住,wsgi应用程序在代理设置中的行为略有不同。如果您还没有开发用于代理的应用程序,那么可以应用 ProxyFix 中间件。

配置nginx

作为一个例子,我们在这里演示如何配置nginx来代理服务器。

基本的nginx配置如下:

location / {
    proxy_set_header        Host $host;
    proxy_set_header        X-Forwarded-For $proxy_add_x_forwarded_for;
    proxy_pass              http://127.0.0.1:8080;
    proxy_redirect          default;
}

因为nginx不为您启动服务器,所以您必须自己启动。你可以写一个 init.d 脚本或在屏幕会话中执行:

$ screen
$ python start-server.py