python - 如何用 flask 扭曲运行?

标签 python flask twisted reverse-proxy

我希望能够在同一端口的不同目录上同时运行多个扭曲的代理服务器,我想我可能会使用 flask。 所以这是我的代码:

from flask import Flask
from twisted.internet import reactor
from twisted.web import proxy, server

app = Flask(__name__)
@app.route('/example')
def index():
    site = server.Site(proxy.ReverseProxyResource('www.example.com', 80, ''.encode("utf-8")))
    reactor.listenTCP(80, site)
    reactor.run()

app.run(port=80, host='My_IP')

但是每当我运行这个脚本时,我都会收到一个内部服务器错误,我假设是因为当在端口 80 上调用 app.run 时,reactor.run也不能在端口 80 上监听。我想知道是否有某种解决方法,或者我做错了什么。非常感谢任何帮助,谢谢!!

最佳答案

您可以使用 Twisted 中的 WSGIResource 而不是 ReverseProxy。

更新:添加了一个更复杂的示例,在/my_flask 中设置了一个 WSGIResource,在/example 中设置了一个 ReverseProxy

from flask import Flask
from twisted.internet import reactor
from twisted.web.proxy import ReverseProxyResource
from twisted.web.resource import Resource
from twisted.web.server import Site
from twisted.web.wsgi import WSGIResource

app = Flask(__name__)


@app.route('/example')
def index():
    return 'My Twisted Flask'

flask_site = WSGIResource(reactor, reactor.getThreadPool(), app)

root = Resource()
root.putChild('my_flask', flask_site)

site_example = ReverseProxyResource('www.example.com', 80, '/')
root.putChild('example', site_example)


reactor.listenTCP(8081, Site(root))
reactor.run()

尝试在你的本地主机上运行上面的代码,然后访问 localhost:8081/my_flask/example 或 localhost:8081/example

关于python - 如何用 flask 扭曲运行?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36880184/

相关文章:

python + 如何删除消息 "cryptography is not installed, use of crypto disabled"

python - 有没有办法从 BigQuery Python 客户端库执行非阻塞 load_job?

python - 从 PyInstaller 包访问 Python 解释器

python - 具有质心约束的 k-means

python - 如何在 python 中执行 <xor> 例如enc_price = pad <xor> 价格

python - 为什么 Flask 重定向到 "GET/? HTTP/1.1"

python - 通过 python (msn) 发送即时消息

python - twisted 和 multiprocessing.Process 如何创建僵尸?

python - 字典中所有列表位置的总和

python-3.x - 无法启动 lig​​httpd 服务守护进程