2016-04-27 77 views
4

我想能够在同一端口上的不同目录上同时运行多个扭曲的代理服务器,并且我想我可能会使用烧瓶。 所以这里是我的代码:如何用烧瓶运行扭曲?

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') 

但每当我运行该脚本,我得到一个内部服务器错误,我假设,因为当app.run被称为端口80,reactor.run不能在80端口监听以及。我想知道是否有这样的工作,或者我做错了什么。任何帮助非常感谢,谢谢!

+0

你尝试使用不同的端口? –

+0

是的,我尝试使用不同的端口。它导致该网站根本不出现 – Cristian

回答

6

您可以使用来自Twisted的WSGIResource is ReverseProxy。

UPDATE:增加了一个更为复杂的例子是设置在/ my_flask一个WSGIResource并在反向代理/例如

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() 

尝试运行上面的本地主机,然后访问本地主机:8081/my_flask /示例或localhost:8081/example

+0

谢谢这实际上工作得很好,唯一的是,我不知道我会在哪里或如何实现代理功能来呈现其他服务器的资源? – Cristian

+0

更新了我的答案 – Eduardo

+1

我试图用那个确切的代码,但我一直得到'没有这样的资源','没有这样的孩子资源' – Cristian

6

您应该试一试klein。它由大多数twisted核心开发人员制作和使用。语法非常类似于flask,因此如果您已经有一个可运行的flask应用程序,则不必重写很多内容。因此,像下面应该工作:

from twisted.internet import reactor 
from twisted.web import proxy, server 
from klein import Klein 

app = Klein() 

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

app.run('localhost', 8000)  # start the klein app on port 8000 and reactor event loop 

链接

+0

我实际上已经尝试过使用克莱因,但我不断收到错误我试试看,去http://stackoverflow.com/questions/37013869/how-do-i-run-klein-with-twisted – Cristian

+0

这个问题的答案是准确的。我忽略了一个事实,即你试图在同一个接口上听同一个端口,这会抛出错误。理论上你可以对80端口的流量进行负载平衡,但这可能是过度的。 –